index
int64 0
731k
| package
stringlengths 2
98
⌀ | name
stringlengths 1
76
| docstring
stringlengths 0
281k
⌀ | code
stringlengths 4
1.07M
⌀ | signature
stringlengths 2
42.8k
⌀ |
---|---|---|---|---|---|
728,595 | tables.group | _g_join | Helper method to correctly concatenate a name child object with the
pathname of this group. | def _g_join(self, name):
"""Helper method to correctly concatenate a name child object with the
pathname of this group."""
if name == "/":
# This case can happen when doing copies
return self._v_pathname
return join_path(self._v_pathname, name)
| (self, name) |
728,599 | tables.group | _g_move | null | def _g_move(self, newparent, newname):
# Move the node to the new location.
oldpath = self._v_pathname
super()._g_move(newparent, newname)
newpath = self._v_pathname
# Update location information in children. This node shouldn't
# be affected since it has already been relocated.
self._v_file._update_node_locations(oldpath, newpath)
| (self, newparent, newname) |
728,600 | tables.group | _g_post_init_hook | null | def _g_post_init_hook(self):
if self._v_new:
if self._v_file.params['PYTABLES_SYS_ATTRS']:
# Save some attributes for the new group on disk.
set_attr = self._v_attrs._g__setattr
# Set the title, class and version attributes.
set_attr('TITLE', self._v_new_title)
set_attr('CLASS', self._c_classid)
set_attr('VERSION', self._v_version)
# Set the default filter properties.
newfilters = self._v_new_filters
if newfilters is None:
# If no filters have been passed in the constructor,
# inherit them from the parent group, but only if they
# have been inherited or explicitly set.
newfilters = getattr(
self._v_parent._v_attrs, 'FILTERS', None)
if newfilters is not None:
set_attr('FILTERS', newfilters)
else:
# If the file has PyTables format, get the VERSION attr
if 'VERSION' in self._v_attrs._v_attrnamessys:
self._v_version = self._v_attrs.VERSION
else:
self._v_version = "0.0 (unknown)"
# We don't need to get more attributes from disk,
# since the most important ones are defined as properties.
| (self) |
728,602 | tables.group | _g_refnode | Insert references to a `childnode` via a `childname`.
Checks that the `childname` is valid and does not exist, then
creates references to the given `childnode` by that `childname`.
The validation of the name can be omitted by setting `validate`
to a false value (this may be useful for adding already existing
nodes to the tree).
| def _g_refnode(self, childnode, childname, validate=True):
"""Insert references to a `childnode` via a `childname`.
Checks that the `childname` is valid and does not exist, then
creates references to the given `childnode` by that `childname`.
The validation of the name can be omitted by setting `validate`
to a false value (this may be useful for adding already existing
nodes to the tree).
"""
# Check for name validity.
if validate:
check_name_validity(childname)
childnode._g_check_name(childname)
# Check if there is already a child with the same name.
# This can be triggered because of the user
# (via node construction or renaming/movement).
# Links are not checked here because they are copied and referenced
# using ``File.get_node`` so they already exist in `self`.
if (not isinstance(childnode, Link)) and childname in self:
raise NodeError(
"group ``%s`` already has a child node named ``%s``"
% (self._v_pathname, childname))
# Show a warning if there is an object attribute with that name.
if childname in self.__dict__:
warnings.warn(
"group ``%s`` already has an attribute named ``%s``; "
"you will not be able to use natural naming "
"to access the child node"
% (self._v_pathname, childname), NaturalNameWarning)
# Check group width limits.
if (len(self._v_children) + len(self._v_hidden) >=
self._v_max_group_width):
self._g_width_warning()
# Update members information.
# Insert references to the new child.
# (Assigned values are entirely irrelevant.)
if isvisiblename(childname):
# Visible node.
self.__members__.insert(0, childname) # enable completion
self._v_children[childname] = None # insert node
if isinstance(childnode, Unknown):
self._v_unknown[childname] = None
elif isinstance(childnode, Link):
self._v_links[childname] = None
elif isinstance(childnode, Leaf):
self._v_leaves[childname] = None
elif isinstance(childnode, Group):
self._v_groups[childname] = None
else:
# Hidden node.
self._v_hidden[childname] = None # insert node
| (self, childnode, childname, validate=True) |
728,603 | tables.group | _g_remove | Remove (recursively if needed) the Group.
This version correctly handles both visible and hidden nodes.
| def _g_remove(self, recursive=False, force=False):
"""Remove (recursively if needed) the Group.
This version correctly handles both visible and hidden nodes.
"""
if self._v_nchildren > 0:
if not (recursive or force):
raise NodeError("group ``%s`` has child nodes; "
"please set `recursive` or `force` to true "
"to remove it"
% (self._v_pathname,))
# First close all the descendents hanging from this group,
# so that it is not possible to use a node that no longer exists.
self._g_close_descendents()
# Remove the node itself from the hierarchy.
super()._g_remove(recursive, force)
| (self, recursive=False, force=False) |
728,606 | tables.group | _g_setfilters | null | def _g_setfilters(self, value):
if not isinstance(value, Filters):
raise TypeError(
f"value is not an instance of `Filters`: {value!r}")
self._v_attrs.FILTERS = value
| (self, value) |
728,608 | tables.group | _g_unrefnode | Remove references to a node.
Removes all references to the named node.
| def _g_unrefnode(self, childname):
"""Remove references to a node.
Removes all references to the named node.
"""
# This can *not* be triggered because of the user.
assert childname in self, \
("group ``%s`` does not have a child node named ``%s``"
% (self._v_pathname, childname))
# Update members information, if needed
if '_v_children' in self.__dict__:
if childname in self._v_children:
# Visible node.
members = self.__members__
member_index = members.index(childname)
del members[member_index] # disables completion
del self._v_children[childname] # remove node
self._v_unknown.pop(childname, None)
self._v_links.pop(childname, None)
self._v_leaves.pop(childname, None)
self._v_groups.pop(childname, None)
else:
# Hidden node.
del self._v_hidden[childname] # remove node
| (self, childname) |
728,611 | tables.group | _g_width_warning | Issue a :exc:`PerformanceWarning` on too many children. | def _g_width_warning(self):
"""Issue a :exc:`PerformanceWarning` on too many children."""
warnings.warn("""\
group ``%s`` is exceeding the recommended maximum number of children (%d); \
be ready to see PyTables asking for *lots* of memory and possibly slow I/O."""
% (self._v_pathname, self._v_max_group_width),
PerformanceWarning)
| (self) |
728,612 | tables.exceptions | HDF5ExtError | A low level HDF5 operation failed.
This exception is raised the low level PyTables components used for
accessing HDF5 files. It usually signals that something is not
going well in the HDF5 library or even at the Input/Output level.
Errors in the HDF5 C library may be accompanied by an extensive
HDF5 back trace on standard error (see also
:func:`tables.silence_hdf5_messages`).
.. versionchanged:: 2.4
Parameters
----------
message
error message
h5bt
This parameter (keyword only) controls the HDF5 back trace
handling. Any keyword arguments other than h5bt is ignored.
* if set to False the HDF5 back trace is ignored and the
:attr:`HDF5ExtError.h5backtrace` attribute is set to None
* if set to True the back trace is retrieved from the HDF5
library and stored in the :attr:`HDF5ExtError.h5backtrace`
attribute as a list of tuples
* if set to "VERBOSE" (default) the HDF5 back trace is
stored in the :attr:`HDF5ExtError.h5backtrace` attribute
and also included in the string representation of the
exception
* if not set (or set to None) the default policy is used
(see :attr:`HDF5ExtError.DEFAULT_H5_BACKTRACE_POLICY`)
| class HDF5ExtError(RuntimeError):
"""A low level HDF5 operation failed.
This exception is raised the low level PyTables components used for
accessing HDF5 files. It usually signals that something is not
going well in the HDF5 library or even at the Input/Output level.
Errors in the HDF5 C library may be accompanied by an extensive
HDF5 back trace on standard error (see also
:func:`tables.silence_hdf5_messages`).
.. versionchanged:: 2.4
Parameters
----------
message
error message
h5bt
This parameter (keyword only) controls the HDF5 back trace
handling. Any keyword arguments other than h5bt is ignored.
* if set to False the HDF5 back trace is ignored and the
:attr:`HDF5ExtError.h5backtrace` attribute is set to None
* if set to True the back trace is retrieved from the HDF5
library and stored in the :attr:`HDF5ExtError.h5backtrace`
attribute as a list of tuples
* if set to "VERBOSE" (default) the HDF5 back trace is
stored in the :attr:`HDF5ExtError.h5backtrace` attribute
and also included in the string representation of the
exception
* if not set (or set to None) the default policy is used
(see :attr:`HDF5ExtError.DEFAULT_H5_BACKTRACE_POLICY`)
"""
# NOTE: in order to avoid circular dependencies between modules the
# _dump_h5_backtrace method is set at initialization time in
# the utilsExtenion.
_dump_h5_backtrace = None
DEFAULT_H5_BACKTRACE_POLICY = "VERBOSE"
"""Default policy for HDF5 backtrace handling
* if set to False the HDF5 back trace is ignored and the
:attr:`HDF5ExtError.h5backtrace` attribute is set to None
* if set to True the back trace is retrieved from the HDF5
library and stored in the :attr:`HDF5ExtError.h5backtrace`
attribute as a list of tuples
* if set to "VERBOSE" (default) the HDF5 back trace is
stored in the :attr:`HDF5ExtError.h5backtrace` attribute
and also included in the string representation of the
exception
This parameter can be set using the
:envvar:`PT_DEFAULT_H5_BACKTRACE_POLICY` environment variable.
Allowed values are "IGNORE" (or "FALSE"), "SAVE" (or "TRUE") and
"VERBOSE" to set the policy to False, True and "VERBOSE"
respectively. The special value "DEFAULT" can be used to reset
the policy to the default value
.. versionadded:: 2.4
"""
@classmethod
def set_policy_from_env(cls):
envmap = {
"IGNORE": False,
"FALSE": False,
"SAVE": True,
"TRUE": True,
"VERBOSE": "VERBOSE",
"DEFAULT": "VERBOSE",
}
oldvalue = cls.DEFAULT_H5_BACKTRACE_POLICY
envvalue = os.environ.get("PT_DEFAULT_H5_BACKTRACE_POLICY", "DEFAULT")
try:
newvalue = envmap[envvalue.upper()]
except KeyError:
warnings.warn("Invalid value for the environment variable "
"'PT_DEFAULT_H5_BACKTRACE_POLICY'. The default "
"policy for HDF5 back trace management in PyTables "
"will be: '%s'" % oldvalue)
else:
cls.DEFAULT_H5_BACKTRACE_POLICY = newvalue
return oldvalue
def __init__(self, *args, **kargs):
super().__init__(*args)
self._h5bt_policy = kargs.get('h5bt', self.DEFAULT_H5_BACKTRACE_POLICY)
if self._h5bt_policy and self._dump_h5_backtrace is not None:
self.h5backtrace = self._dump_h5_backtrace()
"""HDF5 back trace.
Contains the HDF5 back trace as a (possibly empty) list of
tuples. Each tuple has the following format::
(filename, line number, function name, text)
Depending on the value of the *h5bt* parameter passed to the
initializer the h5backtrace attribute can be set to None.
This means that the HDF5 back trace has been simply ignored
(not retrieved from the HDF5 C library error stack) or that
there has been an error (silently ignored) during the HDF5 back
trace retrieval.
.. versionadded:: 2.4
See Also
--------
traceback.format_list : :func:`traceback.format_list`
"""
# XXX: check _dump_h5_backtrace failures
else:
self.h5backtrace = None
def __str__(self):
"""Returns a sting representation of the exception.
The actual result depends on policy set in the initializer
:meth:`HDF5ExtError.__init__`.
.. versionadded:: 2.4
"""
verbose = bool(self._h5bt_policy in ('VERBOSE', 'verbose'))
if verbose and self.h5backtrace:
bt = "\n".join([
"HDF5 error back trace\n",
self.format_h5_backtrace(),
"End of HDF5 error back trace"
])
if len(self.args) == 1 and isinstance(self.args[0], str):
msg = super().__str__()
msg = f"{bt}\n\n{msg}"
elif self.h5backtrace[-1][-1]:
msg = f"{bt}\n\n{self.h5backtrace[-1][-1]}"
else:
msg = bt
else:
msg = super().__str__()
return msg
def format_h5_backtrace(self, backtrace=None):
"""Convert the HDF5 trace back represented as a list of tuples.
(see :attr:`HDF5ExtError.h5backtrace`) into a string.
.. versionadded:: 2.4
"""
if backtrace is None:
backtrace = self.h5backtrace
if backtrace is None:
return 'No HDF5 back trace available'
else:
return ''.join(traceback.format_list(backtrace))
| (*args, **kargs) |
728,613 | tables.exceptions | __init__ | null | def __init__(self, *args, **kargs):
super().__init__(*args)
self._h5bt_policy = kargs.get('h5bt', self.DEFAULT_H5_BACKTRACE_POLICY)
if self._h5bt_policy and self._dump_h5_backtrace is not None:
self.h5backtrace = self._dump_h5_backtrace()
"""HDF5 back trace.
Contains the HDF5 back trace as a (possibly empty) list of
tuples. Each tuple has the following format::
(filename, line number, function name, text)
Depending on the value of the *h5bt* parameter passed to the
initializer the h5backtrace attribute can be set to None.
This means that the HDF5 back trace has been simply ignored
(not retrieved from the HDF5 C library error stack) or that
there has been an error (silently ignored) during the HDF5 back
trace retrieval.
.. versionadded:: 2.4
See Also
--------
traceback.format_list : :func:`traceback.format_list`
"""
# XXX: check _dump_h5_backtrace failures
else:
self.h5backtrace = None
| (self, *args, **kargs) |
728,614 | tables.exceptions | __str__ | Returns a sting representation of the exception.
The actual result depends on policy set in the initializer
:meth:`HDF5ExtError.__init__`.
.. versionadded:: 2.4
| def __str__(self):
"""Returns a sting representation of the exception.
The actual result depends on policy set in the initializer
:meth:`HDF5ExtError.__init__`.
.. versionadded:: 2.4
"""
verbose = bool(self._h5bt_policy in ('VERBOSE', 'verbose'))
if verbose and self.h5backtrace:
bt = "\n".join([
"HDF5 error back trace\n",
self.format_h5_backtrace(),
"End of HDF5 error back trace"
])
if len(self.args) == 1 and isinstance(self.args[0], str):
msg = super().__str__()
msg = f"{bt}\n\n{msg}"
elif self.h5backtrace[-1][-1]:
msg = f"{bt}\n\n{self.h5backtrace[-1][-1]}"
else:
msg = bt
else:
msg = super().__str__()
return msg
| (self) |
728,615 | tables.exceptions | format_h5_backtrace | Convert the HDF5 trace back represented as a list of tuples.
(see :attr:`HDF5ExtError.h5backtrace`) into a string.
.. versionadded:: 2.4
| def format_h5_backtrace(self, backtrace=None):
"""Convert the HDF5 trace back represented as a list of tuples.
(see :attr:`HDF5ExtError.h5backtrace`) into a string.
.. versionadded:: 2.4
"""
if backtrace is None:
backtrace = self.h5backtrace
if backtrace is None:
return 'No HDF5 back trace available'
else:
return ''.join(traceback.format_list(backtrace))
| (self, backtrace=None) |
728,616 | tables.atom | Int16Atom | Defines an atom of type ``int16``. | from tables.atom import Int16Atom
| (shape=(), dflt=0) |
728,624 | tables.description | Int16Col | Defines a non-nested column of a particular type.
The constructor accepts the same arguments as the equivalent
`Atom` class, plus an additional ``pos`` argument for
position information, which is assigned to the `_v_pos`
attribute and an ``attrs`` argument for storing additional metadata
similar to `table.attrs`, which is assigned to the `_v_col_attrs`
attribute.
| from tables.description import Int16Col
| (*args, **kwargs) |
728,632 | tables.atom | Int32Atom | Defines an atom of type ``int32``. | from tables.atom import Int32Atom
| (shape=(), dflt=0) |
728,640 | tables.description | Int32Col | Defines a non-nested column of a particular type.
The constructor accepts the same arguments as the equivalent
`Atom` class, plus an additional ``pos`` argument for
position information, which is assigned to the `_v_pos`
attribute and an ``attrs`` argument for storing additional metadata
similar to `table.attrs`, which is assigned to the `_v_col_attrs`
attribute.
| from tables.description import Int32Col
| (*args, **kwargs) |
728,648 | tables.atom | Int64Atom | Defines an atom of type ``int64``. | from tables.atom import Int64Atom
| (shape=(), dflt=0) |
728,656 | tables.description | Int64Col | Defines a non-nested column of a particular type.
The constructor accepts the same arguments as the equivalent
`Atom` class, plus an additional ``pos`` argument for
position information, which is assigned to the `_v_pos`
attribute and an ``attrs`` argument for storing additional metadata
similar to `table.attrs`, which is assigned to the `_v_col_attrs`
attribute.
| from tables.description import Int64Col
| (*args, **kwargs) |
728,664 | tables.atom | Int8Atom | Defines an atom of type ``int8``. | from tables.atom import Int8Atom
| (shape=(), dflt=0) |
728,672 | tables.description | Int8Col | Defines a non-nested column of a particular type.
The constructor accepts the same arguments as the equivalent
`Atom` class, plus an additional ``pos`` argument for
position information, which is assigned to the `_v_pos`
attribute and an ``attrs`` argument for storing additional metadata
similar to `table.attrs`, which is assigned to the `_v_col_attrs`
attribute.
| from tables.description import Int8Col
| (*args, **kwargs) |
728,680 | tables.atom | IntAtom | Defines an atom of a signed integral type (int kind). | class IntAtom(Atom):
"""Defines an atom of a signed integral type (int kind)."""
kind = 'int'
signed = True
_deftype = 'int32'
_defvalue = 0
__init__ = _abstract_atom_init(_deftype, _defvalue)
| (itemsize=4, shape=(), dflt=0) |
728,688 | tables.description | IntCol | Defines a non-nested column of a particular type.
The constructor accepts the same arguments as the equivalent
`Atom` class, plus an additional ``pos`` argument for
position information, which is assigned to the `_v_pos`
attribute and an ``attrs`` argument for storing additional metadata
similar to `table.attrs`, which is assigned to the `_v_col_attrs`
attribute.
| from tables.description import IntCol
| (*args, **kwargs) |
728,696 | tables.description | IsDescription | Description of the structure of a table or nested column.
This class is designed to be used as an easy, yet meaningful way to
describe the structure of new Table (see :ref:`TableClassDescr`) datasets
or nested columns through the definition of *derived classes*. In order to
define such a class, you must declare it as descendant of IsDescription,
with as many attributes as columns you want in your table. The name of each
attribute will become the name of a column, and its value will hold a
description of it.
Ordinary columns can be described using instances of the Col class (see
:ref:`ColClassDescr`). Nested columns can be described by using classes
derived from IsDescription, instances of it, or name-description
dictionaries. Derived classes can be declared in place (in which case the
column takes the name of the class) or referenced by name.
Nested columns can have a _v_pos special attribute which sets the
*relative* position of the column among sibling columns *also having
explicit positions*. The pos constructor argument of Col instances is used
for the same purpose. Columns with no explicit position will be placed
afterwards in alphanumeric order.
Once you have created a description object, you can pass it to the Table
constructor, where all the information it contains will be used to define
the table structure.
.. rubric:: IsDescription attributes
.. attribute:: _v_pos
Sets the position of a possible nested column description among its
sibling columns. This attribute can be specified *when declaring*
an IsDescription subclass to complement its *metadata*.
.. attribute:: columns
Maps the name of each column in the description to its own descriptive
object. This attribute is *automatically created* when an IsDescription
subclass is declared. Please note that declared columns can no longer
be accessed as normal class variables after its creation.
| class IsDescription(metaclass=MetaIsDescription):
"""Description of the structure of a table or nested column.
This class is designed to be used as an easy, yet meaningful way to
describe the structure of new Table (see :ref:`TableClassDescr`) datasets
or nested columns through the definition of *derived classes*. In order to
define such a class, you must declare it as descendant of IsDescription,
with as many attributes as columns you want in your table. The name of each
attribute will become the name of a column, and its value will hold a
description of it.
Ordinary columns can be described using instances of the Col class (see
:ref:`ColClassDescr`). Nested columns can be described by using classes
derived from IsDescription, instances of it, or name-description
dictionaries. Derived classes can be declared in place (in which case the
column takes the name of the class) or referenced by name.
Nested columns can have a _v_pos special attribute which sets the
*relative* position of the column among sibling columns *also having
explicit positions*. The pos constructor argument of Col instances is used
for the same purpose. Columns with no explicit position will be placed
afterwards in alphanumeric order.
Once you have created a description object, you can pass it to the Table
constructor, where all the information it contains will be used to define
the table structure.
.. rubric:: IsDescription attributes
.. attribute:: _v_pos
Sets the position of a possible nested column description among its
sibling columns. This attribute can be specified *when declaring*
an IsDescription subclass to complement its *metadata*.
.. attribute:: columns
Maps the name of each column in the description to its own descriptive
object. This attribute is *automatically created* when an IsDescription
subclass is declared. Please note that declared columns can no longer
be accessed as normal class variables after its creation.
"""
| () |
728,697 | tables.leaf | Leaf | Abstract base class for all PyTables leaves.
A leaf is a node (see the Node class in :class:`Node`) which hangs from a
group (see the Group class in :class:`Group`) but, unlike a group, it can
not have any further children below it (i.e. it is an end node).
This definition includes all nodes which contain actual data (datasets
handled by the Table - see :ref:`TableClassDescr`, Array -
see :ref:`ArrayClassDescr`, CArray - see :ref:`CArrayClassDescr`, EArray -
see :ref:`EArrayClassDescr`, and VLArray - see :ref:`VLArrayClassDescr`
classes) and unsupported nodes (the UnImplemented
class - :ref:`UnImplementedClassDescr`) these classes do in fact inherit
from Leaf.
.. rubric:: Leaf attributes
These instance variables are provided in addition to those in Node
(see :ref:`NodeClassDescr`):
.. attribute:: byteorder
The byte ordering of the leaf data *on disk*. It will be either
``little`` or ``big``.
.. attribute:: dtype
The NumPy dtype that most closely matches this leaf type.
.. attribute:: extdim
The index of the enlargeable dimension (-1 if none).
.. attribute:: nrows
The length of the main dimension of the leaf data.
.. attribute:: nrowsinbuf
The number of rows that fit in internal input buffers.
You can change this to fine-tune the speed or memory
requirements of your application.
.. attribute:: shape
The shape of data in the leaf.
| class Leaf(Node):
"""Abstract base class for all PyTables leaves.
A leaf is a node (see the Node class in :class:`Node`) which hangs from a
group (see the Group class in :class:`Group`) but, unlike a group, it can
not have any further children below it (i.e. it is an end node).
This definition includes all nodes which contain actual data (datasets
handled by the Table - see :ref:`TableClassDescr`, Array -
see :ref:`ArrayClassDescr`, CArray - see :ref:`CArrayClassDescr`, EArray -
see :ref:`EArrayClassDescr`, and VLArray - see :ref:`VLArrayClassDescr`
classes) and unsupported nodes (the UnImplemented
class - :ref:`UnImplementedClassDescr`) these classes do in fact inherit
from Leaf.
.. rubric:: Leaf attributes
These instance variables are provided in addition to those in Node
(see :ref:`NodeClassDescr`):
.. attribute:: byteorder
The byte ordering of the leaf data *on disk*. It will be either
``little`` or ``big``.
.. attribute:: dtype
The NumPy dtype that most closely matches this leaf type.
.. attribute:: extdim
The index of the enlargeable dimension (-1 if none).
.. attribute:: nrows
The length of the main dimension of the leaf data.
.. attribute:: nrowsinbuf
The number of rows that fit in internal input buffers.
You can change this to fine-tune the speed or memory
requirements of your application.
.. attribute:: shape
The shape of data in the leaf.
"""
# These are a little hard to override, but so are properties.
attrs = Node._v_attrs
"""The associated AttributeSet instance - see :ref:`AttributeSetClassDescr`
(This is an easier-to-write alias of :attr:`Node._v_attrs`."""
title = Node._v_title
"""A description for this node
(This is an easier-to-write alias of :attr:`Node._v_title`)."""
@property
def name(self):
"""The name of this node in its parent group (This is an
easier-to-write alias of :attr:`Node._v_name`)."""
return self._v_name
@property
def chunkshape(self):
"""The HDF5 chunk size for chunked leaves (a tuple).
This is read-only because you cannot change the chunk size of a
leaf once it has been created.
"""
return getattr(self, '_v_chunkshape', None)
@property
def object_id(self):
"""A node identifier, which may change from run to run.
(This is an easier-to-write alias of :attr:`Node._v_objectid`).
.. versionchanged:: 3.0
The *objectID* property has been renamed into *object_id*.
"""
return self._v_objectid
@property
def ndim(self):
"""The number of dimensions of the leaf data.
.. versionadded: 2.4"""
return len(self.shape)
@lazyattr
def filters(self):
"""Filter properties for this leaf.
See Also
--------
Filters
"""
return Filters._from_leaf(self)
@property
def track_times(self):
"""Whether timestamps for the leaf are recorded
If the leaf is not a dataset, this will fail with HDF5ExtError.
The track times dataset creation property does not seem to
survive closing and reopening as of HDF5 1.8.17. Currently,
it may be more accurate to test whether the ctime for the
dataset is 0:
track_times = (leaf._get_obj_timestamps().ctime == 0)
"""
return self._get_obj_track_times()
@property
def maindim(self):
"""The dimension along which iterators work.
Its value is 0 (i.e. the first dimension) when the dataset is not
extendable, and self.extdim (where available) for extendable ones.
"""
if self.extdim < 0:
return 0 # choose the first dimension
return self.extdim
@property
def flavor(self):
"""The type of data object read from this leaf.
It can be any of 'numpy' or 'python'.
You can (and are encouraged to) use this property to get, set
and delete the FLAVOR HDF5 attribute of the leaf. When the leaf
has no such attribute, the default flavor is used..
"""
return self._flavor
@flavor.setter
def flavor(self, flavor):
self._v_file._check_writable()
check_flavor(flavor)
self._v_attrs.FLAVOR = self._flavor = flavor # logs the change
@flavor.deleter
def flavor(self):
del self._v_attrs.FLAVOR
self._flavor = internal_flavor
@property
def size_on_disk(self):
"""
The size of this leaf's data in bytes as it is stored on disk. If the
data is compressed, this shows the compressed size. In the case of
uncompressed, chunked data, this may be slightly larger than the amount
of data, due to partially filled chunks.
"""
return self._get_storage_size()
def __init__(self, parentnode, name,
new=False, filters=None,
byteorder=None, _log=True,
track_times=True):
self._v_new = new
"""Is this the first time the node has been created?"""
self.nrowsinbuf = None
"""
The number of rows that fits in internal input buffers.
You can change this to fine-tune the speed or memory
requirements of your application.
"""
self._flavor = None
"""Private storage for the `flavor` property."""
if new:
# Get filter properties from parent group if not given.
if filters is None:
filters = parentnode._v_filters
self.__dict__['filters'] = filters # bypass the property
if byteorder not in (None, 'little', 'big'):
raise ValueError(
"the byteorder can only take 'little' or 'big' values "
"and you passed: %s" % byteorder)
self.byteorder = byteorder
"""The byte ordering of the leaf data *on disk*."""
self._want_track_times = track_times
# Existing filters need not be read since `filters`
# is a lazy property that automatically handles their loading.
super().__init__(parentnode, name, _log)
def __len__(self):
"""Return the length of the main dimension of the leaf data.
Please note that this may raise an OverflowError on 32-bit platforms
for datasets having more than 2**31-1 rows. This is a limitation of
Python that you can work around by using the nrows or shape attributes.
"""
return self.nrows
def __str__(self):
"""The string representation for this object is its pathname in the
HDF5 object tree plus some additional metainfo."""
filters = []
if self.filters.fletcher32:
filters.append("fletcher32")
if self.filters.complevel:
if self.filters.shuffle:
filters.append("shuffle")
if self.filters.bitshuffle:
filters.append("bitshuffle")
filters.append(f"{self.filters.complib}({self.filters.complevel})")
return (f"{self._v_pathname} ({self.__class__.__name__}"
f"{self.shape}{', '.join(filters)}) {self._v_title!r}")
def _g_post_init_hook(self):
"""Code to be run after node creation and before creation logging.
This method gets or sets the flavor of the leaf.
"""
super()._g_post_init_hook()
if self._v_new: # set flavor of new node
if self._flavor is None:
self._flavor = internal_flavor
else: # flavor set at creation time, do not log
if self._v_file.params['PYTABLES_SYS_ATTRS']:
self._v_attrs._g__setattr('FLAVOR', self._flavor)
else: # get flavor of existing node (if any)
if self._v_file.params['PYTABLES_SYS_ATTRS']:
flavor = getattr(self._v_attrs, 'FLAVOR', internal_flavor)
self._flavor = flavor_alias_map.get(flavor, flavor)
else:
self._flavor = internal_flavor
def _calc_chunkshape(self, expectedrows, rowsize, itemsize):
"""Calculate the shape for the HDF5 chunk."""
# In case of a scalar shape, return the unit chunksize
if self.shape == ():
return (SizeType(1),)
# Compute the chunksize
MB = 1024 * 1024
expected_mb = (expectedrows * rowsize) // MB
chunksize = calc_chunksize(expected_mb)
complib = self.filters.complib
if (complib is not None and
complib.startswith("blosc2") and
self._c_classid in ('TABLE', 'CARRAY', 'EARRAY')):
# Blosc2 can introspect into blocks, so we can increase the
# chunksize for improving HDF5 perf for its internal btree.
# For the time being, this has been implemented efficiently
# just for tables, but in the future *Array objects could also
# be included.
# Use a decent default value for chunksize
chunksize *= 16
# Now, go explore the L3 size and try to find a smarter chunksize
if 'l3_cache_size' in cpu_info:
# In general, is a good idea to set the chunksize equal to L3
l3_cache_size = cpu_info['l3_cache_size']
# cpuinfo sometimes returns cache sizes as strings (like,
# "4096 KB"), so refuse the temptation to guess and use the
# value only when it is an actual int.
# Also, sometimes cpuinfo does not return a correct L3 size;
# so in general, enforcing L3 > L2 is a good sanity check.
l2_cache_size = cpu_info.get('l2_cache_size', "Not found")
if (type(l3_cache_size) is int and
type(l2_cache_size) is int and
l3_cache_size > l2_cache_size):
chunksize = l3_cache_size
# In Blosc2, the chunksize cannot be larger than 2 GB - BLOSC2_MAX_BUFFERSIZE
if chunksize > 2**31 - 32:
chunksize = 2**31 - 32
maindim = self.maindim
# Compute the chunknitems
chunknitems = chunksize // itemsize
# Safeguard against itemsizes being extremely large
if chunknitems == 0:
chunknitems = 1
chunkshape = list(self.shape)
# Check whether trimming the main dimension is enough
chunkshape[maindim] = 1
newchunknitems = np.prod(chunkshape, dtype=SizeType)
if newchunknitems <= chunknitems:
chunkshape[maindim] = chunknitems // newchunknitems
else:
# No, so start trimming other dimensions as well
for j in range(len(chunkshape)):
# Check whether trimming this dimension is enough
chunkshape[j] = 1
newchunknitems = np.prod(chunkshape, dtype=SizeType)
if newchunknitems <= chunknitems:
chunkshape[j] = chunknitems // newchunknitems
break
else:
# Ops, we ran out of the loop without a break
# Set the last dimension to chunknitems
chunkshape[-1] = chunknitems
return tuple(SizeType(s) for s in chunkshape)
def _calc_nrowsinbuf(self):
"""Calculate the number of rows that fits on a PyTables buffer."""
params = self._v_file.params
# Compute the nrowsinbuf
rowsize = self.rowsize
buffersize = params['IO_BUFFER_SIZE']
if rowsize != 0:
nrowsinbuf = buffersize // rowsize
else:
nrowsinbuf = 1
# Safeguard against row sizes being extremely large
if nrowsinbuf == 0:
nrowsinbuf = 1
# If rowsize is too large, issue a Performance warning
maxrowsize = params['BUFFER_TIMES'] * buffersize
if rowsize > maxrowsize:
warnings.warn("""\
The Leaf ``%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 *main*
dimension of this leave. Alternatively, in case you have specified a
very small/large chunksize, you may want to increase/decrease it."""
% (self._v_pathname, maxrowsize),
PerformanceWarning)
return nrowsinbuf
# This method is appropriate for calls to __getitem__ methods
def _process_range(self, start, stop, step, dim=None, warn_negstep=True):
if dim is None:
nrows = self.nrows # self.shape[self.maindim]
else:
nrows = self.shape[dim]
if warn_negstep and step and step < 0:
raise ValueError("slice step cannot be negative")
# if start is not None: start = long(start)
# if stop is not None: stop = long(stop)
# if step is not None: step = long(step)
return slice(start, stop, step).indices(int(nrows))
# This method is appropriate for calls to read() methods
def _process_range_read(self, start, stop, step, warn_negstep=True):
nrows = self.nrows
if start is not None and stop is None and step is None:
# Protection against start greater than available records
# nrows == 0 is a special case for empty objects
if 0 < nrows <= start:
raise IndexError("start of range (%s) is greater than "
"number of rows (%s)" % (start, nrows))
step = 1
if start == -1: # corner case
stop = nrows
else:
stop = start + 1
# Finally, get the correct values (over the main dimension)
start, stop, step = self._process_range(start, stop, step,
warn_negstep=warn_negstep)
return (start, stop, step)
def _g_copy(self, newparent, newname, recursive, _log=True, **kwargs):
# Compute default arguments.
start = kwargs.pop('start', None)
stop = kwargs.pop('stop', None)
step = kwargs.pop('step', None)
title = kwargs.pop('title', self._v_title)
filters = kwargs.pop('filters', self.filters)
chunkshape = kwargs.pop('chunkshape', self.chunkshape)
copyuserattrs = kwargs.pop('copyuserattrs', True)
stats = kwargs.pop('stats', None)
if chunkshape == 'keep':
chunkshape = self.chunkshape # Keep the original chunkshape
elif chunkshape == 'auto':
chunkshape = None # Will recompute chunkshape
# Fix arguments with explicit None values for backwards compatibility.
if title is None:
title = self._v_title
if filters is None:
filters = self.filters
# Create a copy of the object.
(new_node, bytes) = self._g_copy_with_stats(
newparent, newname, start, stop, step,
title, filters, chunkshape, _log, **kwargs)
# Copy user attributes if requested (or the flavor at least).
if copyuserattrs:
self._v_attrs._g_copy(new_node._v_attrs, copyclass=True)
elif 'FLAVOR' in self._v_attrs:
if self._v_file.params['PYTABLES_SYS_ATTRS']:
new_node._v_attrs._g__setattr('FLAVOR', self._flavor)
new_node._flavor = self._flavor # update cached value
# Update statistics if needed.
if stats is not None:
stats['leaves'] += 1
stats['bytes'] += bytes
return new_node
def _g_fix_byteorder_data(self, data, dbyteorder):
"""Fix the byteorder of data passed in constructors."""
dbyteorder = byteorders[dbyteorder]
# If self.byteorder has not been passed as an argument of
# the constructor, then set it to the same value of data.
if self.byteorder is None:
self.byteorder = dbyteorder
# Do an additional in-place byteswap of data if the in-memory
# byteorder doesn't match that of the on-disk. This is the only
# place that we have to do the conversion manually. In all the
# other cases, it will be HDF5 the responsible for doing the
# byteswap properly.
if dbyteorder in ['little', 'big']:
if dbyteorder != self.byteorder:
# if data is not writeable, do a copy first
if not data.flags.writeable:
data = data.copy()
data.byteswap(True)
else:
# Fix the byteorder again, no matter which byteorder have
# specified the user in the constructor.
self.byteorder = "irrelevant"
return data
def _point_selection(self, key):
"""Perform a point-wise selection.
`key` can be any of the following items:
* A boolean array with the same shape than self. Those positions
with True values will signal the coordinates to be returned.
* A numpy array (or list or tuple) with the point coordinates.
This has to be a two-dimensional array of size len(self.shape)
by num_elements containing a list of zero-based values
specifying the coordinates in the dataset of the selected
elements. The order of the element coordinates in the array
specifies the order in which the array elements are iterated
through when I/O is performed. Duplicate coordinate locations
are not checked for.
Return the coordinates array. If this is not possible, raise a
`TypeError` so that the next selection method can be tried out.
This is useful for whatever `Leaf` instance implementing a
point-wise selection.
"""
input_key = key
if type(key) in (list, tuple):
if isinstance(key, tuple) and len(key) > len(self.shape):
raise IndexError(f"Invalid index or slice: {key!r}")
# Try to convert key to a numpy array. If not possible,
# a TypeError will be issued (to be catched later on).
try:
key = toarray(key)
except ValueError:
raise TypeError(f"Invalid index or slice: {key!r}")
elif not isinstance(key, np.ndarray):
raise TypeError(f"Invalid index or slice: {key!r}")
# Protection against empty keys
if len(key) == 0:
return np.array([], dtype="i8")
if key.dtype.kind == 'b':
if not key.shape == self.shape:
raise IndexError(
"Boolean indexing array has incompatible shape")
# Get the True coordinates (64-bit indices!)
coords = np.asarray(key.nonzero(), dtype='i8')
coords = np.transpose(coords)
elif key.dtype.kind == 'i' or key.dtype.kind == 'u':
if len(key.shape) > 2:
raise IndexError(
"Coordinate indexing array has incompatible shape")
elif len(key.shape) == 2:
if key.shape[0] != len(self.shape):
raise IndexError(
"Coordinate indexing array has incompatible shape")
coords = np.asarray(key, dtype="i8")
coords = np.transpose(coords)
else:
# For 1-dimensional datasets
coords = np.asarray(key, dtype="i8")
# handle negative indices
base = coords if coords.base is None else coords.base
if base is input_key:
# never modify the original "key" data
coords = coords.copy()
idx = coords < 0
coords[idx] = (coords + self.shape)[idx]
# bounds check
if np.any(coords < 0) or np.any(coords >= self.shape):
raise IndexError("Index out of bounds")
else:
raise TypeError("Only integer coordinates allowed.")
# We absolutely need a contiguous array
if not coords.flags.contiguous:
coords = coords.copy()
return coords
# Tree manipulation
def remove(self):
"""Remove this node from the hierarchy.
This method has the behavior described
in :meth:`Node._f_remove`. Please note that there is no recursive flag
since leaves do not have child nodes.
"""
self._f_remove(False)
def rename(self, newname):
"""Rename this node in place.
This method has the behavior described in :meth:`Node._f_rename()`.
"""
self._f_rename(newname)
def move(self, newparent=None, newname=None,
overwrite=False, createparents=False):
"""Move or rename this node.
This method has the behavior described in :meth:`Node._f_move`
"""
self._f_move(newparent, newname, overwrite, createparents)
def copy(self, newparent=None, newname=None,
overwrite=False, createparents=False, **kwargs):
"""Copy this node and return the new one.
This method has the behavior described in :meth:`Node._f_copy`. Please
note that there is no recursive flag since leaves do not have child
nodes.
.. warning::
Note that unknown parameters passed to this method will be
ignored, so may want to double check the spelling of these
(i.e. if you write them incorrectly, they will most probably
be ignored).
Parameters
----------
title
The new title for the destination. If omitted or None, the original
title is used.
filters : Filters
Specifying this parameter overrides the original filter properties
in the source node. If specified, it must be an instance of the
Filters class (see :ref:`FiltersClassDescr`). The default is to
copy the filter properties from the source node.
copyuserattrs
You can prevent the user attributes from being copied by setting
this parameter to False. The default is to copy them.
start, stop, step : int
Specify the range of rows to be copied; the default is to copy all
the rows.
stats
This argument may be used to collect statistics on the copy
process. When used, it should be a dictionary with keys 'groups',
'leaves' and 'bytes' having a numeric value. Their values will be
incremented to reflect the number of groups, leaves and bytes,
respectively, that have been copied during the operation.
chunkshape
The chunkshape of the new leaf. It supports a couple of special
values. A value of keep means that the chunkshape will be the same
than original leaf (this is the default). A value of auto means
that a new shape will be computed automatically in order to ensure
best performance when accessing the dataset through the main
dimension. Any other value should be an integer or a tuple
matching the dimensions of the leaf.
"""
return self._f_copy(
newparent, newname, overwrite, createparents, **kwargs)
def truncate(self, size):
"""Truncate the main dimension to be size rows.
If the main dimension previously was larger than this size, the extra
data is lost. If the main dimension previously was shorter, it is
extended, and the extended part is filled with the default values.
The truncation operation can only be applied to *enlargeable* datasets,
else a TypeError will be raised.
"""
# A non-enlargeable arrays (Array, CArray) cannot be truncated
if self.extdim < 0:
raise TypeError("non-enlargeable datasets cannot be truncated")
self._g_truncate(size)
def isvisible(self):
"""Is this node visible?
This method has the behavior described in :meth:`Node._f_isvisible()`.
"""
return self._f_isvisible()
# Attribute handling
def get_attr(self, name):
"""Get a PyTables attribute from this node.
This method has the behavior described in :meth:`Node._f_getattr`.
"""
return self._f_getattr(name)
def set_attr(self, name, value):
"""Set a PyTables attribute for this node.
This method has the behavior described in :meth:`Node._f_setattr()`.
"""
self._f_setattr(name, value)
def del_attr(self, name):
"""Delete a PyTables attribute from this node.
This method has the behavior described in :meth:`Node_f_delAttr`.
"""
self._f_delattr(name)
# Data handling
def flush(self):
"""Flush pending data to disk.
Saves whatever remaining buffered data to disk. It also releases
I/O buffers, so if you are filling many datasets in the same
PyTables session, please call flush() extensively so as to help
PyTables to keep memory requirements low.
"""
self._g_flush()
def _f_close(self, flush=True):
"""Close this node in the tree.
This method has the behavior described in :meth:`Node._f_close`.
Besides that, the optional argument flush tells whether to flush
pending data to disk or not before closing.
"""
if not self._v_isopen:
return # the node is already closed or not initialized
# Only do a flush in case the leaf has an IO buffer. The
# internal buffers of HDF5 will be flushed afterwards during the
# self._g_close() call. Avoiding an unnecessary flush()
# operation accelerates the closing for the unbuffered leaves.
if flush and hasattr(self, "_v_iobuf"):
self.flush()
# Close the dataset and release resources
self._g_close()
# Close myself as a node.
super()._f_close()
def close(self, flush=True):
"""Close this node in the tree.
This method is completely equivalent to :meth:`Leaf._f_close`.
"""
self._f_close(flush)
| (parentnode, name, new=False, filters=None, byteorder=None, _log=True, track_times=True) |
728,699 | tables.leaf | __init__ | null | def __init__(self, parentnode, name,
new=False, filters=None,
byteorder=None, _log=True,
track_times=True):
self._v_new = new
"""Is this the first time the node has been created?"""
self.nrowsinbuf = None
"""
The number of rows that fits in internal input buffers.
You can change this to fine-tune the speed or memory
requirements of your application.
"""
self._flavor = None
"""Private storage for the `flavor` property."""
if new:
# Get filter properties from parent group if not given.
if filters is None:
filters = parentnode._v_filters
self.__dict__['filters'] = filters # bypass the property
if byteorder not in (None, 'little', 'big'):
raise ValueError(
"the byteorder can only take 'little' or 'big' values "
"and you passed: %s" % byteorder)
self.byteorder = byteorder
"""The byte ordering of the leaf data *on disk*."""
self._want_track_times = track_times
# Existing filters need not be read since `filters`
# is a lazy property that automatically handles their loading.
super().__init__(parentnode, name, _log)
| (self, parentnode, name, new=False, filters=None, byteorder=None, _log=True, track_times=True) |
728,719 | tables.node | _g_create | Create a new HDF5 node and return its object identifier. | def _g_create(self):
"""Create a new HDF5 node and return its object identifier."""
raise NotImplementedError
| (self) |
728,728 | tables.node | _g_open | Open an existing HDF5 node and return its object identifier. | def _g_open(self):
"""Open an existing HDF5 node and return its object identifier."""
raise NotImplementedError
| (self) |
728,751 | tables.atom | MetaAtom | Atom metaclass.
This metaclass ensures that data about atom classes gets inserted
into the suitable registries.
| class MetaAtom(type):
"""Atom metaclass.
This metaclass ensures that data about atom classes gets inserted
into the suitable registries.
"""
def __init__(cls, name, bases, dict_):
super().__init__(name, bases, dict_)
kind = dict_.get('kind')
itemsize = dict_.get('itemsize')
type_ = dict_.get('type')
deftype = dict_.get('_deftype')
if kind and deftype:
deftype_from_kind[kind] = deftype
if type_:
all_types.add(type_)
if kind and itemsize and not hasattr(itemsize, '__int__'):
# Atom classes with a non-fixed item size do have an
# ``itemsize``, but it's not a number (e.g. property).
atom_map[kind] = cls
return
if kind: # first definition of kind, make new entry
atom_map[kind] = {}
if itemsize and hasattr(itemsize, '__int__'): # fixed
kind = cls.kind # maybe from superclasses
atom_map[kind][int(itemsize)] = cls
| (name, bases, dict_) |
728,752 | tables.atom | __init__ | null | def __init__(cls, name, bases, dict_):
super().__init__(name, bases, dict_)
kind = dict_.get('kind')
itemsize = dict_.get('itemsize')
type_ = dict_.get('type')
deftype = dict_.get('_deftype')
if kind and deftype:
deftype_from_kind[kind] = deftype
if type_:
all_types.add(type_)
if kind and itemsize and not hasattr(itemsize, '__int__'):
# Atom classes with a non-fixed item size do have an
# ``itemsize``, but it's not a number (e.g. property).
atom_map[kind] = cls
return
if kind: # first definition of kind, make new entry
atom_map[kind] = {}
if itemsize and hasattr(itemsize, '__int__'): # fixed
kind = cls.kind # maybe from superclasses
atom_map[kind][int(itemsize)] = cls
| (cls, name, bases, dict_) |
728,753 | tables.description | MetaIsDescription | Helper metaclass to return the class variables as a dictionary. | class MetaIsDescription(type):
"""Helper metaclass to return the class variables as a dictionary."""
def __new__(mcs, classname, bases, classdict):
"""Return a new class with a "columns" attribute filled."""
newdict = {"columns": {}, }
if '__doc__' in classdict:
newdict['__doc__'] = classdict['__doc__']
for b in bases:
if "columns" in b.__dict__:
newdict["columns"].update(b.__dict__["columns"])
for k in classdict:
# if not (k.startswith('__') or k.startswith('_v_')):
# We let pass _v_ variables to configure class behaviour
if not (k.startswith('__')):
newdict["columns"][k] = classdict[k]
# Return a new class with the "columns" attribute filled
return type.__new__(mcs, classname, bases, newdict)
| (classname, bases, classdict) |
728,754 | tables.description | __new__ | Return a new class with a "columns" attribute filled. | def __new__(mcs, classname, bases, classdict):
"""Return a new class with a "columns" attribute filled."""
newdict = {"columns": {}, }
if '__doc__' in classdict:
newdict['__doc__'] = classdict['__doc__']
for b in bases:
if "columns" in b.__dict__:
newdict["columns"].update(b.__dict__["columns"])
for k in classdict:
# if not (k.startswith('__') or k.startswith('_v_')):
# We let pass _v_ variables to configure class behaviour
if not (k.startswith('__')):
newdict["columns"][k] = classdict[k]
# Return a new class with the "columns" attribute filled
return type.__new__(mcs, classname, bases, newdict)
| (mcs, classname, bases, classdict) |
728,755 | tables.exceptions | NaturalNameWarning | Issued when a non-pythonic name is given for a node.
This is not an error and may even be very useful in certain
contexts, but one should be aware that such nodes cannot be
accessed using natural naming (instead, ``getattr()`` must be
used explicitly).
| class NaturalNameWarning(Warning):
"""Issued when a non-pythonic name is given for a node.
This is not an error and may even be very useful in certain
contexts, but one should be aware that such nodes cannot be
accessed using natural naming (instead, ``getattr()`` must be
used explicitly).
"""
pass
| null |
728,756 | tables.exceptions | NoSuchNodeError | An operation was requested on a node that does not exist.
This exception is raised when an operation gets a path name or a
``(where, name)`` pair leading to a nonexistent node.
| class NoSuchNodeError(NodeError):
"""An operation was requested on a node that does not exist.
This exception is raised when an operation gets a path name or a
``(where, name)`` pair leading to a nonexistent node.
"""
pass
| null |
728,757 | tables.node | Node | Abstract base class for all PyTables nodes.
This is the base class for *all* nodes in a PyTables hierarchy. It is an
abstract class, i.e. it may not be directly instantiated; however, every
node in the hierarchy is an instance of this class.
A PyTables node is always hosted in a PyTables *file*, under a *parent
group*, at a certain *depth* in the node hierarchy. A node knows its own
*name* in the parent group and its own *path name* in the file.
All the previous information is location-dependent, i.e. it may change when
moving or renaming a node in the hierarchy. A node also has
location-independent information, such as its *HDF5 object identifier* and
its *attribute set*.
This class gathers the operations and attributes (both location-dependent
and independent) which are common to all PyTables nodes, whatever their
type is. Nonetheless, due to natural naming restrictions, the names of all
of these members start with a reserved prefix (see the Group class
in :ref:`GroupClassDescr`).
Sub-classes with no children (e.g. *leaf nodes*) may define new methods,
attributes and properties to avoid natural naming restrictions. For
instance, _v_attrs may be shortened to attrs and _f_rename to
rename. However, the original methods and attributes should still be
available.
.. rubric:: Node attributes
.. attribute:: _v_depth
The depth of this node in the tree (an non-negative integer value).
.. attribute:: _v_file
The hosting File instance (see :ref:`FileClassDescr`).
.. attribute:: _v_name
The name of this node in its parent group (a string).
.. attribute:: _v_pathname
The path of this node in the tree (a string).
.. attribute:: _v_objectid
A node identifier (may change from run to run).
.. versionchanged:: 3.0
The *_v_objectID* attribute has been renamed into *_v_object_id*.
| class Node(metaclass=MetaNode):
"""Abstract base class for all PyTables nodes.
This is the base class for *all* nodes in a PyTables hierarchy. It is an
abstract class, i.e. it may not be directly instantiated; however, every
node in the hierarchy is an instance of this class.
A PyTables node is always hosted in a PyTables *file*, under a *parent
group*, at a certain *depth* in the node hierarchy. A node knows its own
*name* in the parent group and its own *path name* in the file.
All the previous information is location-dependent, i.e. it may change when
moving or renaming a node in the hierarchy. A node also has
location-independent information, such as its *HDF5 object identifier* and
its *attribute set*.
This class gathers the operations and attributes (both location-dependent
and independent) which are common to all PyTables nodes, whatever their
type is. Nonetheless, due to natural naming restrictions, the names of all
of these members start with a reserved prefix (see the Group class
in :ref:`GroupClassDescr`).
Sub-classes with no children (e.g. *leaf nodes*) may define new methods,
attributes and properties to avoid natural naming restrictions. For
instance, _v_attrs may be shortened to attrs and _f_rename to
rename. However, the original methods and attributes should still be
available.
.. rubric:: Node attributes
.. attribute:: _v_depth
The depth of this node in the tree (an non-negative integer value).
.. attribute:: _v_file
The hosting File instance (see :ref:`FileClassDescr`).
.. attribute:: _v_name
The name of this node in its parent group (a string).
.. attribute:: _v_pathname
The path of this node in the tree (a string).
.. attribute:: _v_objectid
A node identifier (may change from run to run).
.. versionchanged:: 3.0
The *_v_objectID* attribute has been renamed into *_v_object_id*.
"""
# By default, attributes accept Undo/Redo.
_AttributeSet = AttributeSet
# `_v_parent` is accessed via its file to avoid upwards references.
def _g_getparent(self):
"""The parent :class:`Group` instance"""
(parentpath, nodename) = split_path(self._v_pathname)
return self._v_file._get_node(parentpath)
_v_parent = property(_g_getparent)
# '_v_attrs' is defined as a lazy read-only attribute.
# This saves 0.7s/3.8s.
@lazyattr
def _v_attrs(self):
"""The associated `AttributeSet` instance.
See Also
--------
tables.attributeset.AttributeSet : container for the HDF5 attributes
"""
return self._AttributeSet(self)
# '_v_title' is a direct read-write shorthand for the 'TITLE' attribute
# with the empty string as a default value.
def _g_gettitle(self):
"""A description of this node. A shorthand for TITLE attribute."""
if hasattr(self._v_attrs, 'TITLE'):
return self._v_attrs.TITLE
else:
return ''
def _g_settitle(self, title):
self._v_attrs.TITLE = title
_v_title = property(_g_gettitle, _g_settitle)
# This may be looked up by ``__del__`` when ``__init__`` doesn't get
# to be called. See ticket #144 for more info.
_v_isopen = False
"""Whehter this node is open or not."""
# The ``_log`` argument is only meant to be used by ``_g_copy_as_child()``
# to avoid logging the creation of children nodes of a copied sub-tree.
def __init__(self, parentnode, name, _log=True):
# Remember to assign these values in the root group constructor
# as it does not use this method implementation!
# if the parent node is a softlink, dereference it
if isinstance(parentnode, class_name_dict['SoftLink']):
parentnode = parentnode.dereference()
self._v_file = None
"""The hosting File instance (see :ref:`FileClassDescr`)."""
self._v_isopen = False
"""Whether this node is open or not."""
self._v_pathname = None
"""The path of this node in the tree (a string)."""
self._v_name = None
"""The name of this node in its parent group (a string)."""
self._v_depth = None
"""The depth of this node in the tree (an non-negative integer value).
"""
self._v_maxtreedepth = parentnode._v_file.params['MAX_TREE_DEPTH']
"""Maximum tree depth before warning the user.
.. versionchanged:: 3.0
Renamed into *_v_maxtreedepth* from *_v_maxTreeDepth*.
"""
self._v__deleting = False
"""Is the node being deleted?"""
self._v_objectid = None
"""A node identifier (may change from run to run).
.. versionchanged:: 3.0
The *_v_objectID* attribute has been renamed into *_v_objectid*.
"""
validate = new = self._v_new # set by subclass constructor
# Is the parent node a group? Is it open?
self._g_check_group(parentnode)
parentnode._g_check_open()
file_ = parentnode._v_file
# Will the file be able to host a new node?
if new:
file_._check_writable()
# Bind to the parent node and set location-dependent information.
if new:
# Only new nodes need to be referenced.
# Opened nodes are already known by their parent group.
parentnode._g_refnode(self, name, validate)
self._g_set_location(parentnode, name)
try:
# hdf5extension operations:
# Update node attributes.
self._g_new(parentnode, name, init=True)
# Create or open the node and get its object ID.
if new:
self._v_objectid = self._g_create()
else:
self._v_objectid = self._g_open()
# The node *has* been created, log that.
if new and _log and file_.is_undo_enabled():
self._g_log_create()
# This allows extra operations after creating the node.
self._g_post_init_hook()
except Exception:
# If anything happens, the node must be closed
# to undo every possible registration made so far.
# We do *not* rely on ``__del__()`` doing it later,
# since it might never be called anyway.
self._f_close()
raise
def _g_log_create(self):
self._v_file._log('CREATE', self._v_pathname)
def __del__(self):
# Closed `Node` instances can not be killed and revived.
# Instead, accessing a closed and deleted (from memory, not
# disk) one yields a *new*, open `Node` instance. This is
# because of two reasons:
#
# 1. Predictability. After closing a `Node` and deleting it,
# only one thing can happen when accessing it again: a new,
# open `Node` instance is returned. If closed nodes could be
# revived, one could get either a closed or an open `Node`.
#
# 2. Ease of use. If the user wants to access a closed node
# again, the only condition would be that no references to
# the `Node` instance were left. If closed nodes could be
# revived, the user would also need to force the closed
# `Node` out of memory, which is not a trivial task.
#
if not self._v_isopen:
return # the node is already closed or not initialized
self._v__deleting = True
# If we get here, the `Node` is still open.
try:
node_manager = self._v_file._node_manager
node_manager.drop_node(self, check_unregistered=False)
finally:
# At this point the node can still be open if there is still some
# alive reference around (e.g. if the __del__ method is called
# explicitly by the user).
if self._v_isopen:
self._v__deleting = True
self._f_close()
def _g_pre_kill_hook(self):
"""Code to be called before killing the node."""
pass
def _g_create(self):
"""Create a new HDF5 node and return its object identifier."""
raise NotImplementedError
def _g_open(self):
"""Open an existing HDF5 node and return its object identifier."""
raise NotImplementedError
def _g_check_open(self):
"""Check that the node is open.
If the node is closed, a `ClosedNodeError` is raised.
"""
if not self._v_isopen:
raise ClosedNodeError("the node object is closed")
assert self._v_file.isopen, "found an open node in a closed file"
def _g_set_location(self, parentnode, name):
"""Set location-dependent attributes.
Sets the location-dependent attributes of this node to reflect
that it is placed under the specified `parentnode`, with the
specified `name`.
This also triggers the insertion of file references to this
node. If the maximum recommended tree depth is exceeded, a
`PerformanceWarning` is issued.
"""
file_ = parentnode._v_file
parentdepth = parentnode._v_depth
self._v_file = file_
self._v_isopen = True
root_uep = file_.root_uep
if name.startswith(root_uep):
# This has been called from File._get_node()
assert parentdepth == 0
if root_uep == "/":
self._v_pathname = name
else:
self._v_pathname = name[len(root_uep):]
_, self._v_name = split_path(name)
self._v_depth = name.count("/") - root_uep.count("/") + 1
else:
# If we enter here is because this has been called elsewhere
self._v_name = name
self._v_pathname = join_path(parentnode._v_pathname, name)
self._v_depth = parentdepth + 1
# Check if the node is too deep in the tree.
if parentdepth >= self._v_maxtreedepth:
warnings.warn("""\
node ``%s`` is exceeding the recommended maximum depth (%d);\
be ready to see PyTables asking for *lots* of memory and possibly slow I/O"""
% (self._v_pathname, self._v_maxtreedepth),
PerformanceWarning)
if self._v_pathname != '/':
file_._node_manager.cache_node(self, self._v_pathname)
def _g_update_location(self, newparentpath):
"""Update location-dependent attributes.
Updates location data when an ancestor node has changed its
location in the hierarchy to `newparentpath`. In fact, this
method is expected to be called by an ancestor of this node.
This also triggers the update of file references to this node.
If the maximum recommended node depth is exceeded, a
`PerformanceWarning` is issued. This warning is assured to be
unique.
"""
oldpath = self._v_pathname
newpath = join_path(newparentpath, self._v_name)
newdepth = newpath.count('/')
self._v_pathname = newpath
self._v_depth = newdepth
# Check if the node is too deep in the tree.
if newdepth > self._v_maxtreedepth:
warnings.warn("""\
moved descendent node is exceeding the recommended maximum depth (%d);\
be ready to see PyTables asking for *lots* of memory and possibly slow I/O"""
% (self._v_maxtreedepth,), PerformanceWarning)
node_manager = self._v_file._node_manager
node_manager.rename_node(oldpath, newpath)
# Tell dependent objects about the new location of this node.
self._g_update_dependent()
def _g_del_location(self):
"""Clear location-dependent attributes.
This also triggers the removal of file references to this node.
"""
node_manager = self._v_file._node_manager
pathname = self._v_pathname
if not self._v__deleting:
node_manager.drop_from_cache(pathname)
# Note: node_manager.drop_node do not removes the node form the
# registry if it is still open
node_manager.registry.pop(pathname, None)
self._v_file = None
self._v_isopen = False
self._v_pathname = None
self._v_name = None
self._v_depth = None
def _g_post_init_hook(self):
"""Code to be run after node creation and before creation logging."""
pass
def _g_update_dependent(self):
"""Update dependent objects after a location change.
All dependent objects (but not nodes!) referencing this node
must be updated here.
"""
if '_v_attrs' in self.__dict__:
self._v_attrs._g_update_node_location(self)
def _f_close(self):
"""Close this node in the tree.
This releases all resources held by the node, so it should not
be used again. On nodes with data, it may be flushed to disk.
You should not need to close nodes manually because they are
automatically opened/closed when they are loaded/evicted from
the integrated LRU cache.
"""
# After calling ``_f_close()``, two conditions are met:
#
# 1. The node object is detached from the tree.
# 2. *Every* attribute of the node is removed.
#
# Thus, cleanup operations used in ``_f_close()`` in sub-classes
# must be run *before* calling the method in the superclass.
if not self._v_isopen:
return # the node is already closed
myDict = self.__dict__
# Close the associated `AttributeSet`
# only if it has already been placed in the object's dictionary.
if '_v_attrs' in myDict:
self._v_attrs._g_close()
# Detach the node from the tree if necessary.
self._g_del_location()
# Finally, clear all remaining attributes from the object.
myDict.clear()
# Just add a final flag to signal that the node is closed:
self._v_isopen = False
def _g_remove(self, recursive, force):
"""Remove this node from the hierarchy.
If the node has children, recursive removal must be stated by
giving `recursive` a true value; otherwise, a `NodeError` will
be raised.
If `force` is set to true, the node will be removed no matter it
has children or not (useful for deleting hard links).
It does not log the change.
"""
# Remove the node from the PyTables hierarchy.
parent = self._v_parent
parent._g_unrefnode(self._v_name)
# Close the node itself.
self._f_close()
# hdf5extension operations:
# Remove the node from the HDF5 hierarchy.
self._g_delete(parent)
def _f_remove(self, recursive=False, force=False):
"""Remove this node from the hierarchy.
If the node has children, recursive removal must be stated by giving
recursive a true value; otherwise, a NodeError will be raised.
If the node is a link to a Group object, and you are sure that you want
to delete it, you can do this by setting the force flag to true.
"""
self._g_check_open()
file_ = self._v_file
file_._check_writable()
if file_.is_undo_enabled():
self._g_remove_and_log(recursive, force)
else:
self._g_remove(recursive, force)
def _g_remove_and_log(self, recursive, force):
file_ = self._v_file
oldpathname = self._v_pathname
# Log *before* moving to use the right shadow name.
file_._log('REMOVE', oldpathname)
move_to_shadow(file_, oldpathname)
def _g_move(self, newparent, newname):
"""Move this node in the hierarchy.
Moves the node into the given `newparent`, with the given
`newname`.
It does not log the change.
"""
oldparent = self._v_parent
oldname = self._v_name
oldpathname = self._v_pathname # to move the HDF5 node
# Try to insert the node into the new parent.
newparent._g_refnode(self, newname)
# Remove the node from the new parent.
oldparent._g_unrefnode(oldname)
# Remove location information for this node.
self._g_del_location()
# Set new location information for this node.
self._g_set_location(newparent, newname)
# hdf5extension operations:
# Update node attributes.
self._g_new(newparent, self._v_name, init=False)
# Move the node.
# self._v_parent._g_move_node(oldpathname, self._v_pathname)
self._v_parent._g_move_node(oldparent._v_objectid, oldname,
newparent._v_objectid, newname,
oldpathname, self._v_pathname)
# Tell dependent objects about the new location of this node.
self._g_update_dependent()
def _f_rename(self, newname, overwrite=False):
"""Rename this node in place.
Changes the name of a node to *newname* (a string). If a node with the
same newname already exists and overwrite is true, recursively remove
it before renaming.
"""
self._f_move(newname=newname, overwrite=overwrite)
def _f_move(self, newparent=None, newname=None,
overwrite=False, createparents=False):
"""Move or rename this node.
Moves a node into a new parent group, or changes the name of the
node. newparent can be a Group object (see :ref:`GroupClassDescr`) or a
pathname in string form. If it is not specified or None, the current
parent group is chosen as the new parent. newname must be a string
with a new name. If it is not specified or None, the current name is
chosen as the new name. If createparents is true, the needed groups for
the given new parent group path to exist will be created.
Moving a node across databases is not allowed, nor it is moving a node
*into* itself. These result in a NodeError. However, moving a node
*over* itself is allowed and simply does nothing. Moving over another
existing node is similarly not allowed, unless the optional overwrite
argument is true, in which case that node is recursively removed before
moving.
Usually, only the first argument will be used, effectively moving the
node to a new location without changing its name. Using only the
second argument is equivalent to renaming the node in place.
"""
self._g_check_open()
file_ = self._v_file
oldparent = self._v_parent
oldname = self._v_name
# Set default arguments.
if newparent is None and newname is None:
raise NodeError("you should specify at least "
"a ``newparent`` or a ``newname`` parameter")
if newparent is None:
newparent = oldparent
if newname is None:
newname = oldname
# Get destination location.
if hasattr(newparent, '_v_file'): # from node
newfile = newparent._v_file
newpath = newparent._v_pathname
elif hasattr(newparent, 'startswith'): # from path
newfile = file_
newpath = newparent
else:
raise TypeError("new parent is not a node nor a path: %r"
% (newparent,))
# Validity checks on arguments.
# Is it in the same file?
if newfile is not file_:
raise NodeError("nodes can not be moved across databases; "
"please make a copy of the node")
# The movement always fails if the hosting file can not be modified.
file_._check_writable()
# Moving over itself?
oldpath = oldparent._v_pathname
if newpath == oldpath and newname == oldname:
# This is equivalent to renaming the node to its current name,
# and it does not change the referenced object,
# so it is an allowed no-op.
return
# Moving into itself?
self._g_check_not_contains(newpath)
# Note that the previous checks allow us to go ahead and create
# the parent groups if `createparents` is true. `newparent` is
# used instead of `newpath` to avoid accepting `Node` objects
# when `createparents` is true.
newparent = file_._get_or_create_path(newparent, createparents)
self._g_check_group(newparent) # Is it a group?
# Moving over an existing node?
self._g_maybe_remove(newparent, newname, overwrite)
# Move the node.
oldpathname = self._v_pathname
self._g_move(newparent, newname)
# Log the change.
if file_.is_undo_enabled():
self._g_log_move(oldpathname)
def _g_log_move(self, oldpathname):
self._v_file._log('MOVE', oldpathname, self._v_pathname)
def _g_copy(self, newparent, newname, recursive, _log=True, **kwargs):
"""Copy this node and return the new one.
Creates and returns a copy of the node in the given `newparent`,
with the given `newname`. If `recursive` copy is stated, all
descendents are copied as well. Additional keyword argumens may
affect the way that the copy is made. Unknown arguments must be
ignored. On recursive copies, all keyword arguments must be
passed on to the children invocation of this method.
If `_log` is false, the change is not logged. This is *only*
intended to be used by ``_g_copy_as_child()`` as a means of
optimising sub-tree copies.
"""
raise NotImplementedError
def _g_copy_as_child(self, newparent, **kwargs):
"""Copy this node as a child of another group.
Copies just this node into `newparent`, not recursing children
nor overwriting nodes nor logging the copy. This is intended to
be used when copying whole sub-trees.
"""
return self._g_copy(newparent, self._v_name,
recursive=False, _log=False, **kwargs)
def _f_copy(self, newparent=None, newname=None,
overwrite=False, recursive=False, createparents=False,
**kwargs):
"""Copy this node and return the new node.
Creates and returns a copy of the node, maybe in a different place in
the hierarchy. newparent can be a Group object (see
:ref:`GroupClassDescr`) or a pathname in string form. If it is not
specified or None, the current parent group is chosen as the new
parent. newname must be a string with a new name. If it is not
specified or None, the current name is chosen as the new name. If
recursive copy is stated, all descendants are copied as well. If
createparents is true, the needed groups for the given new parent group
path to exist will be created.
Copying a node across databases is supported but can not be
undone. Copying a node over itself is not allowed, nor it is
recursively copying a node into itself. These result in a
NodeError. Copying over another existing node is similarly not allowed,
unless the optional overwrite argument is true, in which case that node
is recursively removed before copying.
Additional keyword arguments may be passed to customize the copying
process. For instance, title and filters may be changed, user
attributes may be or may not be copied, data may be sub-sampled, stats
may be collected, etc. See the documentation for the particular node
type.
Using only the first argument is equivalent to copying the node to a
new location without changing its name. Using only the second argument
is equivalent to making a copy of the node in the same group.
"""
self._g_check_open()
srcfile = self._v_file
srcparent = self._v_parent
srcname = self._v_name
dstparent = newparent
dstname = newname
# Set default arguments.
if dstparent is None and dstname is None:
raise NodeError("you should specify at least "
"a ``newparent`` or a ``newname`` parameter")
if dstparent is None:
dstparent = srcparent
if dstname is None:
dstname = srcname
# Get destination location.
if hasattr(dstparent, '_v_file'): # from node
dstfile = dstparent._v_file
dstpath = dstparent._v_pathname
elif hasattr(dstparent, 'startswith'): # from path
dstfile = srcfile
dstpath = dstparent
else:
raise TypeError("new parent is not a node nor a path: %r"
% (dstparent,))
# Validity checks on arguments.
if dstfile is srcfile:
# Copying over itself?
srcpath = srcparent._v_pathname
if dstpath == srcpath and dstname == srcname:
raise NodeError(
"source and destination nodes are the same node: ``%s``"
% self._v_pathname)
# Recursively copying into itself?
if recursive:
self._g_check_not_contains(dstpath)
# Note that the previous checks allow us to go ahead and create
# the parent groups if `createparents` is true. `dstParent` is
# used instead of `dstPath` because it may be in other file, and
# to avoid accepting `Node` objects when `createparents` is
# true.
dstparent = srcfile._get_or_create_path(dstparent, createparents)
self._g_check_group(dstparent) # Is it a group?
# Copying to another file with undo enabled?
if dstfile is not srcfile and srcfile.is_undo_enabled():
warnings.warn("copying across databases can not be undone "
"nor redone from this database",
UndoRedoWarning)
# Copying over an existing node?
self._g_maybe_remove(dstparent, dstname, overwrite)
# Copy the node.
# The constructor of the new node takes care of logging.
return self._g_copy(dstparent, dstname, recursive, **kwargs)
def _f_isvisible(self):
"""Is this node visible?"""
self._g_check_open()
return isvisiblepath(self._v_pathname)
def _g_check_group(self, node):
# Node must be defined in order to define a Group.
# However, we need to know Group here.
# Using class_name_dict avoids a circular import.
if not isinstance(node, class_name_dict['Node']):
raise TypeError("new parent is not a registered node: %s"
% node._v_pathname)
if not isinstance(node, class_name_dict['Group']):
raise TypeError("new parent node ``%s`` is not a group"
% node._v_pathname)
def _g_check_not_contains(self, pathname):
# The not-a-TARDIS test. ;)
mypathname = self._v_pathname
if (mypathname == '/' # all nodes fall below the root group
or pathname == mypathname
or pathname.startswith(mypathname + '/')):
raise NodeError("can not move or recursively copy node ``%s`` "
"into itself" % mypathname)
def _g_maybe_remove(self, parent, name, overwrite):
if name in parent:
if not overwrite:
raise NodeError(
f"destination group ``{parent._v_pathname}`` already "
f"has a node named ``{name}``; you may want to use the "
f"``overwrite`` argument")
parent._f_get_child(name)._f_remove(True)
def _g_check_name(self, name):
"""Check validity of name for this particular kind of node.
This is invoked once the standard HDF5 and natural naming checks
have successfully passed.
"""
if name.startswith('_i_'):
# This is reserved for table index groups.
raise ValueError(
"node name starts with reserved prefix ``_i_``: %s" % name)
def _f_getattr(self, name):
"""Get a PyTables attribute from this node.
If the named attribute does not exist, an AttributeError is
raised.
"""
return getattr(self._v_attrs, name)
def _f_setattr(self, name, value):
"""Set a PyTables attribute for this node.
If the node already has a large number of attributes, a
PerformanceWarning is issued.
"""
setattr(self._v_attrs, name, value)
def _f_delattr(self, name):
"""Delete a PyTables attribute from this node.
If the named attribute does not exist, an AttributeError is
raised.
"""
delattr(self._v_attrs, name)
# </attribute handling>
| (parentnode, name, _log=True) |
728,759 | tables.node | __init__ | null | def __init__(self, parentnode, name, _log=True):
# Remember to assign these values in the root group constructor
# as it does not use this method implementation!
# if the parent node is a softlink, dereference it
if isinstance(parentnode, class_name_dict['SoftLink']):
parentnode = parentnode.dereference()
self._v_file = None
"""The hosting File instance (see :ref:`FileClassDescr`)."""
self._v_isopen = False
"""Whether this node is open or not."""
self._v_pathname = None
"""The path of this node in the tree (a string)."""
self._v_name = None
"""The name of this node in its parent group (a string)."""
self._v_depth = None
"""The depth of this node in the tree (an non-negative integer value).
"""
self._v_maxtreedepth = parentnode._v_file.params['MAX_TREE_DEPTH']
"""Maximum tree depth before warning the user.
.. versionchanged:: 3.0
Renamed into *_v_maxtreedepth* from *_v_maxTreeDepth*.
"""
self._v__deleting = False
"""Is the node being deleted?"""
self._v_objectid = None
"""A node identifier (may change from run to run).
.. versionchanged:: 3.0
The *_v_objectID* attribute has been renamed into *_v_objectid*.
"""
validate = new = self._v_new # set by subclass constructor
# Is the parent node a group? Is it open?
self._g_check_group(parentnode)
parentnode._g_check_open()
file_ = parentnode._v_file
# Will the file be able to host a new node?
if new:
file_._check_writable()
# Bind to the parent node and set location-dependent information.
if new:
# Only new nodes need to be referenced.
# Opened nodes are already known by their parent group.
parentnode._g_refnode(self, name, validate)
self._g_set_location(parentnode, name)
try:
# hdf5extension operations:
# Update node attributes.
self._g_new(parentnode, name, init=True)
# Create or open the node and get its object ID.
if new:
self._v_objectid = self._g_create()
else:
self._v_objectid = self._g_open()
# The node *has* been created, log that.
if new and _log and file_.is_undo_enabled():
self._g_log_create()
# This allows extra operations after creating the node.
self._g_post_init_hook()
except Exception:
# If anything happens, the node must be closed
# to undo every possible registration made so far.
# We do *not* rely on ``__del__()`` doing it later,
# since it might never be called anyway.
self._f_close()
raise
| (self, parentnode, name, _log=True) |
728,760 | tables.node | _f_close | Close this node in the tree.
This releases all resources held by the node, so it should not
be used again. On nodes with data, it may be flushed to disk.
You should not need to close nodes manually because they are
automatically opened/closed when they are loaded/evicted from
the integrated LRU cache.
| def _f_close(self):
"""Close this node in the tree.
This releases all resources held by the node, so it should not
be used again. On nodes with data, it may be flushed to disk.
You should not need to close nodes manually because they are
automatically opened/closed when they are loaded/evicted from
the integrated LRU cache.
"""
# After calling ``_f_close()``, two conditions are met:
#
# 1. The node object is detached from the tree.
# 2. *Every* attribute of the node is removed.
#
# Thus, cleanup operations used in ``_f_close()`` in sub-classes
# must be run *before* calling the method in the superclass.
if not self._v_isopen:
return # the node is already closed
myDict = self.__dict__
# Close the associated `AttributeSet`
# only if it has already been placed in the object's dictionary.
if '_v_attrs' in myDict:
self._v_attrs._g_close()
# Detach the node from the tree if necessary.
self._g_del_location()
# Finally, clear all remaining attributes from the object.
myDict.clear()
# Just add a final flag to signal that the node is closed:
self._v_isopen = False
| (self) |
728,773 | tables.node | _g_copy | Copy this node and return the new one.
Creates and returns a copy of the node in the given `newparent`,
with the given `newname`. If `recursive` copy is stated, all
descendents are copied as well. Additional keyword argumens may
affect the way that the copy is made. Unknown arguments must be
ignored. On recursive copies, all keyword arguments must be
passed on to the children invocation of this method.
If `_log` is false, the change is not logged. This is *only*
intended to be used by ``_g_copy_as_child()`` as a means of
optimising sub-tree copies.
| def _g_copy(self, newparent, newname, recursive, _log=True, **kwargs):
"""Copy this node and return the new one.
Creates and returns a copy of the node in the given `newparent`,
with the given `newname`. If `recursive` copy is stated, all
descendents are copied as well. Additional keyword argumens may
affect the way that the copy is made. Unknown arguments must be
ignored. On recursive copies, all keyword arguments must be
passed on to the children invocation of this method.
If `_log` is false, the change is not logged. This is *only*
intended to be used by ``_g_copy_as_child()`` as a means of
optimising sub-tree copies.
"""
raise NotImplementedError
| (self, newparent, newname, recursive, _log=True, **kwargs) |
728,784 | tables.node | _g_post_init_hook | Code to be run after node creation and before creation logging. | def _g_post_init_hook(self):
"""Code to be run after node creation and before creation logging."""
pass
| (self) |
728,792 | tables.exceptions | NodeError | Invalid hierarchy manipulation operation requested.
This exception is raised when the user requests an operation on the
hierarchy which can not be run because of the current layout of the
tree. This includes accessing nonexistent nodes, moving or copying
or creating over an existing node, non-recursively removing groups
with children, and other similarly invalid operations.
A node in a PyTables database cannot be simply overwritten by
replacing it. Instead, the old node must be removed explicitely
before another one can take its place. This is done to protect
interactive users from inadvertedly deleting whole trees of data by
a single erroneous command.
| class NodeError(AttributeError, LookupError):
"""Invalid hierarchy manipulation operation requested.
This exception is raised when the user requests an operation on the
hierarchy which can not be run because of the current layout of the
tree. This includes accessing nonexistent nodes, moving or copying
or creating over an existing node, non-recursively removing groups
with children, and other similarly invalid operations.
A node in a PyTables database cannot be simply overwritten by
replacing it. Instead, the old node must be removed explicitely
before another one can take its place. This is done to protect
interactive users from inadvertedly deleting whole trees of data by
a single erroneous command.
"""
pass
| null |
728,793 | tables.atom | ObjectAtom | Defines an atom of type object.
This class is meant to fit *any* kind of Python object in a row of a
VLArray dataset by using pickle behind the scenes. Due to the fact that
you can not foresee how long will be the output of the pickle
serialization (i.e. the atom already has a *variable* length), you can only
fit *one object per row*. However, you can still group several objects in a
single tuple or list and pass it to the :meth:`VLArray.append` method.
Object atoms do not accept parameters and they cause the reads of rows to
always return Python objects. You can regard object atoms as an easy way to
save an arbitrary number of generic Python objects in a VLArray dataset.
| class ObjectAtom(_BufferedAtom):
"""Defines an atom of type object.
This class is meant to fit *any* kind of Python object in a row of a
VLArray dataset by using pickle behind the scenes. Due to the fact that
you can not foresee how long will be the output of the pickle
serialization (i.e. the atom already has a *variable* length), you can only
fit *one object per row*. However, you can still group several objects in a
single tuple or list and pass it to the :meth:`VLArray.append` method.
Object atoms do not accept parameters and they cause the reads of rows to
always return Python objects. You can regard object atoms as an easy way to
save an arbitrary number of generic Python objects in a VLArray dataset.
"""
kind = 'object'
type = 'object'
base = UInt8Atom()
def _tobuffer(self, object_):
return pickle.dumps(object_, pickle.HIGHEST_PROTOCOL)
def fromarray(self, array):
# We have to check for an empty array because of a possible
# bug in HDF5 which makes it claim that a dataset has one
# record when in fact it is empty.
if array.size == 0:
return None
return pickle.loads(array.tobytes())
| () |
728,794 | tables.atom | __repr__ | null | def __repr__(self):
return '%s()' % self.__class__.__name__
| (self) |
728,795 | tables.atom | _tobuffer | null | def _tobuffer(self, object_):
return pickle.dumps(object_, pickle.HIGHEST_PROTOCOL)
| (self, object_) |
728,796 | tables.atom | fromarray | null | def fromarray(self, array):
# We have to check for an empty array because of a possible
# bug in HDF5 which makes it claim that a dataset has one
# record when in fact it is empty.
if array.size == 0:
return None
return pickle.loads(array.tobytes())
| (self, array) |
728,797 | tables.atom | toarray | null | def toarray(self, object_):
buffer_ = self._tobuffer(object_)
array = np.ndarray(buffer=buffer_, dtype=self.base.dtype,
shape=len(buffer_))
return array
| (self, object_) |
728,798 | tables.exceptions | OldIndexWarning | Unsupported index format.
This warning is issued when an index in an unsupported format is
found. The index will be marked as invalid and will behave as if
doesn't exist.
| class OldIndexWarning(Warning):
"""Unsupported index format.
This warning is issued when an index in an unsupported format is
found. The index will be marked as invalid and will behave as if
doesn't exist.
"""
pass
| null |
728,799 | tables.exceptions | PerformanceWarning | Warning for operations which may cause a performance drop.
This warning is issued when an operation is made on the database
which may cause it to slow down on future operations (i.e. making
the node tree grow too much).
| class PerformanceWarning(Warning):
"""Warning for operations which may cause a performance drop.
This warning is issued when an operation is made on the database
which may cause it to slow down on future operations (i.e. making
the node tree grow too much).
"""
pass
| null |
728,800 | tables.atom | PseudoAtom | Pseudo-atoms can only be used in ``VLArray`` nodes.
They can be recognised because they also have `kind`, `type` and
`shape` attributes, but no `size`, `itemsize` or `dflt` ones.
Instead, they have a `base` atom which defines the elements used
for storage.
| class PseudoAtom:
"""Pseudo-atoms can only be used in ``VLArray`` nodes.
They can be recognised because they also have `kind`, `type` and
`shape` attributes, but no `size`, `itemsize` or `dflt` ones.
Instead, they have a `base` atom which defines the elements used
for storage.
"""
def __repr__(self):
return '%s()' % self.__class__.__name__
def toarray(self, object_):
"""Convert an `object_` into an array of base atoms."""
raise NotImplementedError
def fromarray(self, array):
"""Convert an `array` of base atoms into an object."""
raise NotImplementedError
| () |
728,802 | tables.atom | fromarray | Convert an `array` of base atoms into an object. | def fromarray(self, array):
"""Convert an `array` of base atoms into an object."""
raise NotImplementedError
| (self, array) |
728,803 | tables.atom | toarray | Convert an `object_` into an array of base atoms. | def toarray(self, object_):
"""Convert an `object_` into an array of base atoms."""
raise NotImplementedError
| (self, object_) |
728,804 | tables.atom | ReferenceAtom | Defines an atom of type object to read references.
This atom is read-only.
| class ReferenceAtom(Atom):
"""Defines an atom of type object to read references.
This atom is read-only.
"""
kind = 'reference'
type = 'object'
_deftype = 'NoneType'
_defvalue = None
@property
def itemsize(self):
"""Size in bytes of a single item in the atom."""
return self.dtype.base.itemsize
def __init__(self, shape=()):
Atom.__init__(self, self.type, shape, self._defvalue)
def __repr__(self):
return f'ReferenceAtom(shape={self.shape})'
| (shape=()) |
728,806 | tables.atom | __init__ | null | def __init__(self, shape=()):
Atom.__init__(self, self.type, shape, self._defvalue)
| (self, shape=()) |
728,808 | tables.atom | __repr__ | null | def __repr__(self):
return f'ReferenceAtom(shape={self.shape})'
| (self) |
728,813 | tables.atom | StringAtom | Defines an atom of type string.
The item size is the *maximum* length in characters of strings.
| class StringAtom(Atom):
"""Defines an atom of type string.
The item size is the *maximum* length in characters of strings.
"""
kind = 'string'
type = 'string'
_defvalue = b''
@property
def itemsize(self):
"""Size in bytes of a sigle item in the atom."""
return self.dtype.base.itemsize
def __init__(self, itemsize, shape=(), dflt=_defvalue):
if not hasattr(itemsize, '__int__') or int(itemsize) < 0:
raise ValueError("invalid item size for kind ``%s``: %r; "
"it must be a positive integer"
% ('string', itemsize))
Atom.__init__(self, 'S%d' % itemsize, shape, dflt)
| (itemsize, shape=(), dflt=b'') |
728,815 | tables.atom | __init__ | null | def __init__(self, itemsize, shape=(), dflt=_defvalue):
if not hasattr(itemsize, '__int__') or int(itemsize) < 0:
raise ValueError("invalid item size for kind ``%s``: %r; "
"it must be a positive integer"
% ('string', itemsize))
Atom.__init__(self, 'S%d' % itemsize, shape, dflt)
| (self, itemsize, shape=(), dflt=b'') |
728,821 | tables.description | StringCol | Defines a non-nested column of a particular type.
The constructor accepts the same arguments as the equivalent
`Atom` class, plus an additional ``pos`` argument for
position information, which is assigned to the `_v_pos`
attribute and an ``attrs`` argument for storing additional metadata
similar to `table.attrs`, which is assigned to the `_v_col_attrs`
attribute.
| from tables.description import StringCol
| (*args, **kwargs) |
728,829 | tables.table | Table | This class represents heterogeneous datasets in an HDF5 file.
Tables are leaves (see the Leaf class in :ref:`LeafClassDescr`) whose data
consists of a unidimensional sequence of *rows*, where each row contains
one or more *fields*. Fields have an associated unique *name* and
*position*, with the first field having position 0. All rows have the same
fields, which are arranged in *columns*.
Fields can have any type supported by the Col class (see
:ref:`ColClassDescr`) and its descendants, which support multidimensional
data. Moreover, a field can be *nested* (to an arbitrary depth), meaning
that it includes further fields inside. A field named x inside a nested
field a in a table can be accessed as the field a/x (its *path name*) from
the table.
The structure of a table is declared by its description, which is made
available in the Table.description attribute (see :class:`Table`).
This class provides new methods to read, write and search table data
efficiently. It also provides special Python methods to allow accessing
the table as a normal sequence or array (with extended slicing supported).
PyTables supports *in-kernel* searches working simultaneously on several
columns using complex conditions. These are faster than selections using
Python expressions. See the :meth:`Table.where` method for more
information on in-kernel searches.
Non-nested columns can be *indexed*. Searching an indexed column can be
several times faster than searching a non-nested one. Search methods
automatically take advantage of indexing where available.
When iterating a table, an object from the Row (see :ref:`RowClassDescr`)
class is used. This object allows to read and write data one row at a
time, as well as to perform queries which are not supported by in-kernel
syntax (at a much lower speed, of course).
Objects of this class support access to individual columns via *natural
naming* through the :attr:`Table.cols` accessor. Nested columns are
mapped to Cols instances, and non-nested ones to Column instances.
See the Column class in :ref:`ColumnClassDescr` for examples of this
feature.
Parameters
----------
parentnode
The parent :class:`Group` object.
.. versionchanged:: 3.0
Renamed from *parentNode* to *parentnode*.
name : str
The name of this node in its parent group.
description
An IsDescription subclass or a dictionary where the keys are the field
names, and the values the type definitions. In addition, a pure NumPy
dtype is accepted. If None, the table metadata is read from disk,
else, it's taken from previous parameters.
title
Sets a TITLE attribute on the HDF5 table entity.
filters : Filters
An instance of the Filters class that provides information about the
desired I/O filters to be applied during the life of this object.
expectedrows
A user estimate about the number of rows that will be on table. If not
provided, the default value is ``EXPECTED_ROWS_TABLE`` (see
``tables/parameters.py``). If you plan to save bigger tables, try
providing a guess; this will optimize the HDF5 B-Tree creation and
management process time and memory used.
chunkshape
The shape of the data chunk to be read or written as a single HDF5 I/O
operation. The filters are applied to those chunks of data. Its rank
for tables has to be 1. If ``None``, a sensible value is calculated
based on the `expectedrows` parameter (which is recommended).
byteorder
The byteorder of the data *on-disk*, specified as 'little' or 'big'. If
this is not specified, the byteorder is that of the platform, unless
you passed a recarray as the `description`, in which case the recarray
byteorder will be chosen.
track_times
Whether time data associated with the leaf are recorded (object
access time, raw data modification time, metadata change time, object
birth time); default True. Semantics of these times depend on their
implementation in the HDF5 library: refer to documentation of the
H5O_info_t data structure. As of HDF5 1.8.15, only ctime (metadata
change time) is implemented.
.. versionadded:: 3.4.3
Notes
-----
The instance variables below are provided in addition to those in
Leaf (see :ref:`LeafClassDescr`). Please note that there are several
col* dictionaries to ease retrieving information about a column
directly by its path name, avoiding the need to walk through
Table.description or Table.cols.
.. rubric:: Table attributes
.. attribute:: coldescrs
Maps the name of a column to its Col description (see
:ref:`ColClassDescr`).
.. attribute:: coldflts
Maps the name of a column to its default value.
.. attribute:: coldtypes
Maps the name of a column to its NumPy data type.
.. attribute:: colindexed
Is the column which name is used as a key indexed?
.. attribute:: colinstances
Maps the name of a column to its Column (see
:ref:`ColumnClassDescr`) or Cols (see :ref:`ColsClassDescr`)
instance.
.. attribute:: colnames
A list containing the names of *top-level* columns in the table.
.. attribute:: colpathnames
A list containing the pathnames of *bottom-level* columns in
the table.
These are the leaf columns obtained when walking the table
description left-to-right, bottom-first. Columns inside a
nested column have slashes (/) separating name components in
their pathname.
.. attribute:: cols
A Cols instance that provides *natural naming* access to
non-nested (Column, see :ref:`ColumnClassDescr`) and nested
(Cols, see :ref:`ColsClassDescr`) columns.
.. attribute:: coltypes
Maps the name of a column to its PyTables data type.
.. attribute:: description
A Description instance (see :ref:`DescriptionClassDescr`)
reflecting the structure of the table.
.. attribute:: extdim
The index of the enlargeable dimension (always 0 for tables).
.. attribute:: indexed
Does this table have any indexed columns?
.. attribute:: nrows
The current number of rows in the table.
| class Table(tableextension.Table, Leaf):
"""This class represents heterogeneous datasets in an HDF5 file.
Tables are leaves (see the Leaf class in :ref:`LeafClassDescr`) whose data
consists of a unidimensional sequence of *rows*, where each row contains
one or more *fields*. Fields have an associated unique *name* and
*position*, with the first field having position 0. All rows have the same
fields, which are arranged in *columns*.
Fields can have any type supported by the Col class (see
:ref:`ColClassDescr`) and its descendants, which support multidimensional
data. Moreover, a field can be *nested* (to an arbitrary depth), meaning
that it includes further fields inside. A field named x inside a nested
field a in a table can be accessed as the field a/x (its *path name*) from
the table.
The structure of a table is declared by its description, which is made
available in the Table.description attribute (see :class:`Table`).
This class provides new methods to read, write and search table data
efficiently. It also provides special Python methods to allow accessing
the table as a normal sequence or array (with extended slicing supported).
PyTables supports *in-kernel* searches working simultaneously on several
columns using complex conditions. These are faster than selections using
Python expressions. See the :meth:`Table.where` method for more
information on in-kernel searches.
Non-nested columns can be *indexed*. Searching an indexed column can be
several times faster than searching a non-nested one. Search methods
automatically take advantage of indexing where available.
When iterating a table, an object from the Row (see :ref:`RowClassDescr`)
class is used. This object allows to read and write data one row at a
time, as well as to perform queries which are not supported by in-kernel
syntax (at a much lower speed, of course).
Objects of this class support access to individual columns via *natural
naming* through the :attr:`Table.cols` accessor. Nested columns are
mapped to Cols instances, and non-nested ones to Column instances.
See the Column class in :ref:`ColumnClassDescr` for examples of this
feature.
Parameters
----------
parentnode
The parent :class:`Group` object.
.. versionchanged:: 3.0
Renamed from *parentNode* to *parentnode*.
name : str
The name of this node in its parent group.
description
An IsDescription subclass or a dictionary where the keys are the field
names, and the values the type definitions. In addition, a pure NumPy
dtype is accepted. If None, the table metadata is read from disk,
else, it's taken from previous parameters.
title
Sets a TITLE attribute on the HDF5 table entity.
filters : Filters
An instance of the Filters class that provides information about the
desired I/O filters to be applied during the life of this object.
expectedrows
A user estimate about the number of rows that will be on table. If not
provided, the default value is ``EXPECTED_ROWS_TABLE`` (see
``tables/parameters.py``). If you plan to save bigger tables, try
providing a guess; this will optimize the HDF5 B-Tree creation and
management process time and memory used.
chunkshape
The shape of the data chunk to be read or written as a single HDF5 I/O
operation. The filters are applied to those chunks of data. Its rank
for tables has to be 1. If ``None``, a sensible value is calculated
based on the `expectedrows` parameter (which is recommended).
byteorder
The byteorder of the data *on-disk*, specified as 'little' or 'big'. If
this is not specified, the byteorder is that of the platform, unless
you passed a recarray as the `description`, in which case the recarray
byteorder will be chosen.
track_times
Whether time data associated with the leaf are recorded (object
access time, raw data modification time, metadata change time, object
birth time); default True. Semantics of these times depend on their
implementation in the HDF5 library: refer to documentation of the
H5O_info_t data structure. As of HDF5 1.8.15, only ctime (metadata
change time) is implemented.
.. versionadded:: 3.4.3
Notes
-----
The instance variables below are provided in addition to those in
Leaf (see :ref:`LeafClassDescr`). Please note that there are several
col* dictionaries to ease retrieving information about a column
directly by its path name, avoiding the need to walk through
Table.description or Table.cols.
.. rubric:: Table attributes
.. attribute:: coldescrs
Maps the name of a column to its Col description (see
:ref:`ColClassDescr`).
.. attribute:: coldflts
Maps the name of a column to its default value.
.. attribute:: coldtypes
Maps the name of a column to its NumPy data type.
.. attribute:: colindexed
Is the column which name is used as a key indexed?
.. attribute:: colinstances
Maps the name of a column to its Column (see
:ref:`ColumnClassDescr`) or Cols (see :ref:`ColsClassDescr`)
instance.
.. attribute:: colnames
A list containing the names of *top-level* columns in the table.
.. attribute:: colpathnames
A list containing the pathnames of *bottom-level* columns in
the table.
These are the leaf columns obtained when walking the table
description left-to-right, bottom-first. Columns inside a
nested column have slashes (/) separating name components in
their pathname.
.. attribute:: cols
A Cols instance that provides *natural naming* access to
non-nested (Column, see :ref:`ColumnClassDescr`) and nested
(Cols, see :ref:`ColsClassDescr`) columns.
.. attribute:: coltypes
Maps the name of a column to its PyTables data type.
.. attribute:: description
A Description instance (see :ref:`DescriptionClassDescr`)
reflecting the structure of the table.
.. attribute:: extdim
The index of the enlargeable dimension (always 0 for tables).
.. attribute:: indexed
Does this table have any indexed columns?
.. attribute:: nrows
The current number of rows in the table.
"""
# Class identifier.
_c_classid = 'TABLE'
@lazyattr
def row(self):
"""The associated Row instance (see :ref:`RowClassDescr`)."""
return tableextension.Row(self)
@lazyattr
def dtype(self):
"""The NumPy ``dtype`` that most closely matches this table."""
return self.description._v_dtype
@property
def shape(self):
"""The shape of this table."""
return (self.nrows,)
@property
def rowsize(self):
"""The size in bytes of each row in the table."""
return self.description._v_dtype.itemsize
@property
def size_in_memory(self):
"""The size of this table's data in bytes when it is fully loaded into
memory. This may be used in combination with size_on_disk to calculate
the compression ratio of the data."""
return self.nrows * self.rowsize
@lazyattr
def _v_iobuf(self):
"""A buffer for doing I/O."""
return self._get_container(self.nrowsinbuf)
@lazyattr
def _v_wdflts(self):
"""The defaults for writing in recarray format."""
# First, do a check to see whether we need to set default values
# different from 0 or not.
for coldflt in self.coldflts.values():
if isinstance(coldflt, np.ndarray) or coldflt:
break
else:
# No default different from 0 found. Returning None.
return None
wdflts = self._get_container(1)
for colname, coldflt in self.coldflts.items():
ra = get_nested_field(wdflts, colname)
ra[:] = coldflt
return wdflts
@lazyattr
def _colunaligned(self):
"""The pathnames of unaligned, *unidimensional* columns."""
colunaligned, rarr = [], self._get_container(0)
for colpathname in self.colpathnames:
carr = get_nested_field(rarr, colpathname)
if not carr.flags.aligned and carr.ndim == 1:
colunaligned.append(colpathname)
return frozenset(colunaligned)
# **************** WARNING! ***********************
# This function can be called during the destruction time of a table
# so measures have been taken so that it doesn't have to revive
# another node (which can fool the LRU cache). The solution devised
# has been to add a cache for autoindex (Table._autoindex), populate
# it in creation time of the cache (which is a safe period) and then
# update the cache whenever it changes.
# This solves the error when running test_indexes.py ManyNodesTestCase.
# F. Alted 2007-04-20
# **************************************************
@property
def autoindex(self):
"""Automatically keep column indexes up to date?
Setting this value states whether existing indexes should be
automatically updated after an append operation or recomputed
after an index-invalidating operation (i.e. removal and
modification of rows). The default is true.
This value gets into effect whenever a column is altered. If you
don't have automatic indexing activated and you want to do an an
immediate update use `Table.flush_rows_to_index()`; for an immediate
reindexing of invalidated indexes, use `Table.reindex_dirty()`.
This value is persistent.
.. versionchanged:: 3.0
The *autoIndex* property has been renamed into *autoindex*.
"""
if self._autoindex is None:
try:
indexgroup = self._v_file._get_node(_index_pathname_of(self))
except NoSuchNodeError:
self._autoindex = default_auto_index # update cache
return self._autoindex
else:
self._autoindex = indexgroup.auto # update cache
return self._autoindex
else:
# The value is in cache, return it
return self._autoindex
@autoindex.setter
def autoindex(self, auto):
auto = bool(auto)
try:
indexgroup = self._v_file._get_node(_index_pathname_of(self))
except NoSuchNodeError:
indexgroup = create_indexes_table(self)
indexgroup.auto = auto
# Update the cache in table instance as well
self._autoindex = auto
@property
def indexedcolpathnames(self):
"""List of pathnames of indexed columns in the table."""
return [_colpname
for _colpname in self.colpathnames
if self.colindexed[_colpname]]
@property
def colindexes(self):
"""A dictionary with the indexes of the indexed columns."""
return _ColIndexes((_colpname, self.cols._f_col(_colpname).index)
for _colpname in self.colpathnames
if self.colindexed[_colpname])
@property
def _dirtyindexes(self):
"""Whether some index in table is dirty."""
return self._condition_cache._nailcount > 0
def __init__(self, parentnode, name,
description=None, title="", filters=None,
expectedrows=None, chunkshape=None,
byteorder=None, _log=True, track_times=True):
self._v_new = new = description is not None
"""Is this the first time the node has been created?"""
self._v_new_title = title
"""New title for this node."""
self._v_new_filters = filters
"""New filter properties for this node."""
self.extdim = 0 # Tables only have one dimension currently
"""The index of the enlargeable dimension (always 0 for tables)."""
self._v_recarray = None
"""A structured array to be stored in the table."""
self._rabyteorder = None
"""The computed byteorder of the self._v_recarray."""
if expectedrows is None:
expectedrows = parentnode._v_file.params['EXPECTED_ROWS_TABLE']
self._v_expectedrows = expectedrows
"""The expected number of rows to be stored in the table."""
self.nrows = SizeType(0)
"""The current number of rows in the table."""
self.description = None
"""A Description instance (see :ref:`DescriptionClassDescr`)
reflecting the structure of the table."""
self._time64colnames = []
"""The names of ``Time64`` columns."""
self._strcolnames = []
"""The names of ``String`` columns."""
self._colenums = {}
"""Maps the name of an enumerated column to its ``Enum`` instance."""
self._v_chunkshape = None
"""Private storage for the `chunkshape` property of the leaf."""
self.indexed = False
"""Does this table have any indexed columns?"""
self._indexedrows = 0
"""Number of rows indexed in disk."""
self._unsaved_indexedrows = 0
"""Number of rows indexed in memory but still not in disk."""
self._listoldindexes = []
"""The list of columns with old indexes."""
self._autoindex = None
"""Private variable that caches the value for autoindex."""
self.colnames = []
"""A list containing the names of *top-level* columns in the table."""
self.colpathnames = []
"""A list containing the pathnames of *bottom-level* columns in the
table.
These are the leaf columns obtained when walking the
table description left-to-right, bottom-first. Columns inside a
nested column have slashes (/) separating name components in
their pathname.
"""
self.colinstances = {}
"""Maps the name of a column to its Column (see
:ref:`ColumnClassDescr`) or Cols (see :ref:`ColsClassDescr`)
instance."""
self.coldescrs = {}
"""Maps the name of a column to its Col description (see
:ref:`ColClassDescr`)."""
self.coltypes = {}
"""Maps the name of a column to its PyTables data type."""
self.coldtypes = {}
"""Maps the name of a column to its NumPy data type."""
self.coldflts = {}
"""Maps the name of a column to its default value."""
self.colindexed = {}
"""Is the column which name is used as a key indexed?"""
self._use_index = False
"""Whether an index can be used or not in a search. Boolean."""
self._where_condition = None
"""Condition function and argument list for selection of values."""
self._seqcache_key = None
"""The key under which to save a query's results (list of row indexes)
or None to not save."""
max_slots = parentnode._v_file.params['COND_CACHE_SLOTS']
self._condition_cache = CacheDict(max_slots)
"""Cache of already compiled conditions."""
self._exprvars_cache = {}
"""Cache of variables participating in numexpr expressions."""
self._enabled_indexing_in_queries = True
"""Is indexing enabled in queries? *Use only for testing.*"""
self._empty_array_cache = {}
"""Cache of empty arrays."""
self._v_dtype = None
"""The NumPy datatype fopr this table."""
self.cols = None
"""
A Cols instance that provides *natural naming* access to non-nested
(Column, see :ref:`ColumnClassDescr`) and nested (Cols, see
:ref:`ColsClassDescr`) columns.
"""
self._dirtycache = True
"""Whether the data caches are dirty or not. Initially set to yes."""
self._descflavor = None
"""Temporarily keeps the flavor of a description with data."""
# Initialize this object in case is a new Table
# Try purely descriptive description objects.
if new and isinstance(description, dict):
# Dictionary case
self.description = Description(description,
ptparams=parentnode._v_file.params)
elif new and (type(description) == type(IsDescription)
and issubclass(description, IsDescription)):
# IsDescription subclass case
descr = description()
self.description = Description(descr.columns,
ptparams=parentnode._v_file.params)
elif new and isinstance(description, Description):
# It is a Description instance already
self.description = description
# No description yet?
if new and self.description is None:
# Try NumPy dtype instances
if isinstance(description, np.dtype):
tup = descr_from_dtype(description,
ptparams=parentnode._v_file.params)
self.description, self._rabyteorder = tup
# No description yet?
if new and self.description is None:
# Try structured array description objects.
try:
self._descflavor = flavor = flavor_of(description)
except TypeError: # probably not an array
pass
else:
if flavor == 'python':
nparray = np.rec.array(description)
else:
nparray = array_as_internal(description, flavor)
self.nrows = nrows = SizeType(nparray.size)
# If `self._v_recarray` is set, it will be used as the
# initial buffer.
if nrows > 0:
self._v_recarray = nparray
tup = descr_from_dtype(nparray.dtype,
ptparams=parentnode._v_file.params)
self.description, self._rabyteorder = tup
# No description yet?
if new and self.description is None:
raise TypeError(
"the ``description`` argument is not of a supported type: "
"``IsDescription`` subclass, ``Description`` instance, "
"dictionary, or structured array")
# Check the chunkshape parameter
if new and chunkshape is not None:
if isinstance(chunkshape, (int, np.integer)):
chunkshape = (chunkshape,)
try:
chunkshape = tuple(chunkshape)
except TypeError:
raise TypeError(
"`chunkshape` parameter must be an integer or sequence "
"and you passed a %s" % type(chunkshape))
if len(chunkshape) != 1:
raise ValueError("`chunkshape` rank (length) must be 1: %r"
% (chunkshape,))
self._v_chunkshape = tuple(SizeType(s) for s in chunkshape)
super().__init__(parentnode, name, new, filters, byteorder, _log,
track_times)
def _g_post_init_hook(self):
# We are putting here the index-related issues
# as well as filling general info for table
# This is needed because we need first the index objects created
# First, get back the flavor of input data (if any) for
# `Leaf._g_post_init_hook()`.
self._flavor, self._descflavor = self._descflavor, None
super()._g_post_init_hook()
# Create a cols accessor.
self.cols = Cols(self, self.description)
# Place the `Cols` and `Column` objects into `self.colinstances`.
colinstances, cols = self.colinstances, self.cols
for colpathname in self.description._v_pathnames:
colinstances[colpathname] = cols._g_col(colpathname)
if self._v_new:
# Columns are never indexed on creation.
self.colindexed = {cpn: False for cpn in self.colpathnames}
return
# The following code is only for opened tables.
# Do the indexes group exist?
indexesgrouppath = _index_pathname_of(self)
igroup = indexesgrouppath in self._v_file
oldindexes = False
for colobj in self.description._f_walk(type="Col"):
colname = colobj._v_pathname
# Is this column indexed?
if igroup:
indexname = _index_pathname_of_column(self, colname)
indexed = indexname in self._v_file
self.colindexed[colname] = indexed
if indexed:
column = self.cols._g_col(colname)
indexobj = column.index
if isinstance(indexobj, OldIndex):
indexed = False # Not a vaild index
oldindexes = True
self._listoldindexes.append(colname)
else:
# Tell the condition cache about columns with dirty
# indexes.
if indexobj.dirty:
self._condition_cache.nail()
else:
indexed = False
self.colindexed[colname] = False
if indexed:
self.indexed = True
if oldindexes: # this should only appear under 2.x Pro
warnings.warn(
"table ``%s`` has column indexes with PyTables 1.x format. "
"Unfortunately, this format is not supported in "
"PyTables 2.x series. Note that you can use the "
"``ptrepack`` utility in order to recreate the indexes. "
"The 1.x indexed columns found are: %s" %
(self._v_pathname, self._listoldindexes),
OldIndexWarning)
# It does not matter to which column 'indexobj' belongs,
# since their respective index objects share
# the same number of elements.
if self.indexed:
self._indexedrows = indexobj.nelements
self._unsaved_indexedrows = self.nrows - self._indexedrows
# Put the autoindex value in a cache variable
self._autoindex = self.autoindex
def _calc_nrowsinbuf(self):
"""Calculate the number of rows that fits on a PyTables buffer."""
params = self._v_file.params
# Compute the nrowsinbuf
rowsize = self.rowsize
buffersize = params['IO_BUFFER_SIZE']
if rowsize != 0:
nrowsinbuf = buffersize // rowsize
# The number of rows in buffer needs to be an exact multiple of
# chunkshape[0] for queries using indexed columns.
# Fixes #319 and probably #409 too.
nrowsinbuf -= nrowsinbuf % self.chunkshape[0]
else:
nrowsinbuf = 1
# tableextension.pyx performs an assertion
# to make sure nrowsinbuf is greater than or
# equal to the chunksize.
# See gh-206 and gh-238
if self.chunkshape is not None:
if nrowsinbuf < self.chunkshape[0]:
nrowsinbuf = self.chunkshape[0]
# Safeguard against row sizes being extremely large
if nrowsinbuf == 0:
nrowsinbuf = 1
# If rowsize is too large, issue a Performance warning
maxrowsize = params['BUFFER_TIMES'] * buffersize
if rowsize > maxrowsize:
warnings.warn("""\
The Table ``%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 *main*
dimension of this leave. Alternatively, in case you have specified a
very small/large chunksize, you may want to increase/decrease it."""
% (self._v_pathname, maxrowsize),
PerformanceWarning)
return nrowsinbuf
def _getemptyarray(self, dtype):
# Acts as a cache for empty arrays
key = dtype
if key in self._empty_array_cache:
return self._empty_array_cache[key]
else:
self._empty_array_cache[
key] = arr = np.empty(shape=0, dtype=key)
return arr
def _get_container(self, shape):
"""Get the appropriate buffer for data depending on table
nestedness."""
# This is *much* faster than the numpy.rec.array counterpart
return np.empty(shape=shape, dtype=self._v_dtype)
def _get_type_col_names(self, type_):
"""Returns a list containing 'type_' column names."""
return [colobj._v_pathname
for colobj in self.description._f_walk('Col')
if colobj.type == type_]
def _get_enum_map(self):
"""Return mapping from enumerated column names to `Enum` instances."""
enumMap = {}
for colobj in self.description._f_walk('Col'):
if colobj.kind == 'enum':
enumMap[colobj._v_pathname] = colobj.enum
return enumMap
def _g_create(self):
"""Create a new table on disk."""
# Warning against assigning too much columns...
# F. Alted 2005-06-05
maxColumns = self._v_file.params['MAX_COLUMNS']
if (len(self.description._v_names) > maxColumns):
warnings.warn(
"table ``%s`` is exceeding the recommended "
"maximum number of columns (%d); "
"be ready to see PyTables asking for *lots* of memory "
"and possibly slow I/O" % (self._v_pathname, maxColumns),
PerformanceWarning)
# 1. Create the HDF5 table (some parameters need to be computed).
# Fix the byteorder of the recarray and update the number of
# expected rows if necessary
if self._v_recarray is not None:
self._v_recarray = self._g_fix_byteorder_data(self._v_recarray,
self._rabyteorder)
if len(self._v_recarray) > self._v_expectedrows:
self._v_expectedrows = len(self._v_recarray)
# Compute a sensible chunkshape
if self._v_chunkshape is None:
self._v_chunkshape = self._calc_chunkshape(
self._v_expectedrows, self.rowsize, self.rowsize)
# Correct the byteorder, if still needed
if self.byteorder is None:
self.byteorder = sys.byteorder
# Cache some data which is already in the description.
# This is necessary to happen before creation time in order
# to be able to populate the self._v_wdflts
self._cache_description_data()
# After creating the table, ``self._v_objectid`` needs to be
# set because it is needed for setting attributes afterwards.
self._v_objectid = self._create_table(
self._v_new_title, self.filters.complib or '', obversion)
self._v_recarray = None # not useful anymore
self._rabyteorder = None # not useful anymore
# 2. Compute or get chunk shape and buffer size parameters.
self.nrowsinbuf = self._calc_nrowsinbuf()
# 3. Get field fill attributes from the table description and
# set them on disk.
if self._v_file.params['PYTABLES_SYS_ATTRS']:
set_attr = self._v_attrs._g__setattr
for i, colobj in enumerate(self.description._f_walk(type="Col")):
fieldname = "FIELD_%d_FILL" % i
set_attr(fieldname, colobj.dflt)
return self._v_objectid
def _g_open(self):
"""Opens a table from disk and read the metadata on it.
Creates an user description on the flight to easy the access to
the actual data.
"""
# 1. Open the HDF5 table and get some data from it.
self._v_objectid, description, chunksize = self._get_info()
self._v_expectedrows = self.nrows # the actual number of rows
# 2. Create an instance description to host the record fields.
validate = not self._v_file._isPTFile # only for non-PyTables files
self.description = Description(description, validate=validate,
ptparams=self._v_file.params)
# 3. Compute or get chunk shape and buffer size parameters.
if chunksize == 0:
self._v_chunkshape = self._calc_chunkshape(
self._v_expectedrows, self.rowsize, self.rowsize)
else:
self._v_chunkshape = (chunksize,)
self.nrowsinbuf = self._calc_nrowsinbuf()
# 4. If there are field fill attributes, get them from disk and
# set them in the table description.
if self._v_file.params['PYTABLES_SYS_ATTRS']:
if "FIELD_0_FILL" in self._v_attrs._f_list("sys"):
i = 0
get_attr = self._v_attrs.__getattr__
for objcol in self.description._f_walk(type="Col"):
colname = objcol._v_pathname
# Get the default values for each column
fieldname = "FIELD_%s_FILL" % i
defval = get_attr(fieldname)
if defval is not None:
objcol.dflt = defval
else:
warnings.warn("could not load default value "
"for the ``%s`` column of table ``%s``; "
"using ``%r`` instead"
% (colname, self._v_pathname,
objcol.dflt))
defval = objcol.dflt
i += 1
# Set also the correct value in the desc._v_dflts dictionary
for descr in self.description._f_walk(type="Description"):
for name in descr._v_names:
objcol = descr._v_colobjects[name]
if isinstance(objcol, Col):
descr._v_dflts[objcol._v_name] = objcol.dflt
# 5. Cache some data which is already in the description.
self._cache_description_data()
return self._v_objectid
def _cache_description_data(self):
"""Cache some data which is already in the description.
Some information is extracted from `self.description` to build
some useful (but redundant) structures:
* `self.colnames`
* `self.colpathnames`
* `self.coldescrs`
* `self.coltypes`
* `self.coldtypes`
* `self.coldflts`
* `self._v_dtype`
* `self._time64colnames`
* `self._strcolnames`
* `self._colenums`
"""
self.colnames = list(self.description._v_names)
self.colpathnames = [
col._v_pathname for col in self.description._f_walk()
if not hasattr(col, '_v_names')] # bottom-level
# Find ``time64`` column names.
self._time64colnames = self._get_type_col_names('time64')
# Find ``string`` column names.
self._strcolnames = self._get_type_col_names('string')
# Get a mapping of enumerated columns to their `Enum` instances.
self._colenums = self._get_enum_map()
# Get info about columns
for colobj in self.description._f_walk(type="Col"):
colname = colobj._v_pathname
# Get the column types, types and defaults
self.coldescrs[colname] = colobj
self.coltypes[colname] = colobj.type
self.coldtypes[colname] = colobj.dtype
self.coldflts[colname] = colobj.dflt
# Assign _v_dtype for this table
self._v_dtype = self.description._v_dtype
def _get_column_instance(self, colpathname):
"""Get the instance of the column with the given `colpathname`.
If the column does not exist in the table, a `KeyError` is
raised.
"""
try:
return functools.reduce(
getattr, colpathname.split('/'), self.description)
except AttributeError:
raise KeyError("table ``%s`` does not have a column named ``%s``"
% (self._v_pathname, colpathname))
_check_column = _get_column_instance
def _disable_indexing_in_queries(self):
"""Force queries not to use indexing.
*Use only for testing.*
"""
if not self._enabled_indexing_in_queries:
return # already disabled
# The nail avoids setting/getting compiled conditions in/from
# the cache where indexing is used.
self._condition_cache.nail()
self._enabled_indexing_in_queries = False
def _enable_indexing_in_queries(self):
"""Allow queries to use indexing.
*Use only for testing.*
"""
if self._enabled_indexing_in_queries:
return # already enabled
self._condition_cache.unnail()
self._enabled_indexing_in_queries = True
def _required_expr_vars(self, expression, uservars, depth=1):
"""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. This mechanism will not work as expected if this
method is not used *directly* from an API callable. To disable
this mechanism, just specify a mapping as `uservars`.
Nested columns and columns from other tables are not allowed
(`TypeError` and `ValueError` are raised, respectively). Also,
non-column variable values are converted to NumPy arrays.
`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._exprvars_cache
if expression not in exprvarscache:
# Protection against growing the cache too much
if len(exprvarscache) > 256:
# Remove 10 (arbitrary) elements from the cache
for k in list(exprvarscache)[: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 ne.expressions.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:
# We use specified depth to get the frame where the API
# callable using this method is called. For instance:
#
# * ``table._required_expr_vars()`` (depth 0) is called by
# * ``table._where()`` (depth 1) is called by
# * ``table.where()`` (depth 2) is called by
# * user-space functions (depth 3)
user_frame = sys._getframe(depth)
user_locals = user_frame.f_locals
user_globals = user_frame.f_globals
colinstances = self.colinstances
tblfile, tblpath = self._v_file, self._v_pathname
# Look for the required variables first among the ones
# explicitly provided by the user, then among implicit columns,
# then among external variables (only if no explicit variables).
reqvars = {}
for var in exprvars:
# Get the value.
if uservars is not None and var in uservars:
val = uservars[var]
elif var in colinstances:
val = colinstances[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, 'pathname'): # non-nested column
if val.shape[1:] != ():
raise NotImplementedError(
"variable ``%s`` refers to "
"a multidimensional column, "
"not yet supported in conditions, sorry" % var)
if (val._table_file is not tblfile or
val._table_path != tblpath):
raise ValueError("variable ``%s`` refers to a column "
"which is not part of table ``%s``"
% (var, tblpath))
if val.dtype.str[1:] == 'u8':
raise NotImplementedError(
"variable ``%s`` refers to "
"a 64-bit unsigned integer column, "
"not yet supported in conditions, sorry; "
"please use regular Python selections" % var)
elif hasattr(val, '_v_colpathnames'): # nested column
raise TypeError(
"variable ``%s`` refers to a nested column, "
"not allowed in conditions" % var)
else: # only non-column values are converted to arrays
# XXX: not 100% sure about this
if isinstance(val, str):
val = np.asarray(val.encode('ascii'))
else:
val = np.asarray(val)
reqvars[var] = val
return reqvars
def _get_condition_key(self, condition, condvars):
"""Get the condition cache key for `condition` with `condvars`.
Currently, the key is a tuple of `condition`, column variables
names, normal variables names, column paths and variable paths
(all are tuples).
"""
# Variable names for column and normal variables.
colnames, varnames = [], []
# Column paths and types for each of the previous variable.
colpaths, vartypes = [], []
for (var, val) in condvars.items():
if hasattr(val, 'pathname'): # column
colnames.append(var)
colpaths.append(val.pathname)
else: # array
try:
varnames.append(var)
vartypes.append(ne.necompiler.getType(val)) # expensive
except ValueError:
# This is more clear than the error given by Numexpr.
raise TypeError("variable ``%s`` has data type ``%s``, "
"not allowed in conditions"
% (var, val.dtype.name))
colnames, varnames = tuple(colnames), tuple(varnames)
colpaths, vartypes = tuple(colpaths), tuple(vartypes)
condkey = (condition, colnames, varnames, colpaths, vartypes)
return condkey
def _compile_condition(self, condition, condvars):
"""Compile the `condition` and extract usable index conditions.
This method returns an instance of ``CompiledCondition``. See
the ``compile_condition()`` function in the ``conditions``
module for more information about the compilation process.
This method makes use of the condition cache when possible.
"""
# Look up the condition in the condition cache.
condcache = self._condition_cache
condkey = self._get_condition_key(condition, condvars)
compiled = condcache.get(condkey)
if compiled:
return compiled.with_replaced_vars(condvars) # bingo!
# Bad luck, the condition must be parsed and compiled.
# Fortunately, the key provides some valuable information. ;)
(condition, colnames, varnames, colpaths, vartypes) = condkey
# Extract more information from referenced columns.
# start with normal variables
typemap = dict(list(zip(varnames, vartypes)))
indexedcols = []
for colname in colnames:
col = condvars[colname]
# Extract types from *all* the given variables.
coltype = col.dtype.type
typemap[colname] = _nxtype_from_nptype[coltype]
# Get the set of columns with usable indexes.
if (self._enabled_indexing_in_queries # no in-kernel searches
and self.colindexed[col.pathname] and not col.index.dirty):
indexedcols.append(colname)
indexedcols = frozenset(indexedcols)
# Now let ``compile_condition()`` do the Numexpr-related job.
compiled = compile_condition(condition, typemap, indexedcols)
# Check that there actually are columns in the condition.
if not set(compiled.parameters).intersection(set(colnames)):
raise ValueError("there are no columns taking part "
"in condition ``%s``" % (condition,))
# Store the compiled condition in the cache and return it.
condcache[condkey] = compiled
return compiled.with_replaced_vars(condvars)
def will_query_use_indexing(self, condition, condvars=None):
"""Will a query for the condition use indexing?
The meaning of the condition and *condvars* arguments is the same as in
the :meth:`Table.where` method. If condition can use indexing, this
method returns a frozenset with the path names of the columns whose
index is usable. Otherwise, it returns an empty list.
This method is mainly intended for testing. Keep in mind that changing
the set of indexed columns or their dirtiness may make this method
return different values for the same arguments at different times.
"""
# Compile the condition and extract usable index conditions.
condvars = self._required_expr_vars(condition, condvars, depth=2)
compiled = self._compile_condition(condition, condvars)
# Return the columns in indexed expressions
idxcols = [condvars[var].pathname for var in compiled.index_variables]
return frozenset(idxcols)
def where(self, condition, condvars=None,
start=None, stop=None, step=None):
r"""Iterate over values fulfilling a condition.
This method returns a Row iterator (see :ref:`RowClassDescr`) which
only selects rows in the table that satisfy the given condition (an
expression-like string).
The condvars mapping may be used to define the variable names appearing
in the condition. condvars should consist of identifier-like strings
pointing to Column (see :ref:`ColumnClassDescr`) instances *of this
table*, or to other values (which will be converted to arrays). A
default set of condition variables is provided where each top-level,
non-nested column with an identifier-like name appears. Variables in
condvars override the default ones.
When condvars is not provided or None, the current local and global
namespace is sought instead of condvars. The previous mechanism is
mostly intended for interactive usage. To disable it, just specify a
(maybe empty) mapping as condvars.
If a range is supplied (by setting some of the start, stop or step
parameters), only the rows in that range and fulfilling the condition
are used. The meaning of the start, stop and step parameters is the
same as for Python slices.
When possible, indexed columns participating in the condition will be
used to speed up the search. It is recommended that you place the
indexed columns as left and out in the condition as possible. Anyway,
this method has always better performance than regular Python
selections on the table.
You can mix this method with regular Python selections in order to
support even more complex queries. It is strongly recommended that you
pass the most restrictive condition as the parameter to this method if
you want to achieve maximum performance.
.. warning::
When in the middle of a table row iterator, you should not
use methods that can change the number of rows in the table
(like :meth:`Table.append` or :meth:`Table.remove_rows`) or
unexpected errors will happen.
Examples
--------
::
passvalues = [ row['col3'] for row in
table.where('(col1 > 0) & (col2 <= 20)', step=5)
if your_function(row['col2']) ]
print("Values that pass the cuts:", passvalues)
.. note::
A special care should be taken when the query condition includes
string literals.
Let's assume that the table ``table`` has the following
structure::
class Record(IsDescription):
col1 = StringCol(4) # 4-character String of bytes
col2 = IntCol()
col3 = FloatCol()
The type of "col1" corresponds to strings of bytes.
Any condition involving "col1" should be written using the
appropriate type for string literals in order to avoid
:exc:`TypeError`\ s.
The code below will fail with a :exc:`TypeError`::
condition = 'col1 == "AAAA"'
for record in table.where(condition): # TypeError in Python3
# do something with "record"
The reason is that in Python 3 "condition" implies a comparison
between a string of bytes ("col1" contents) and a unicode literal
("AAAA").
The correct way to write the condition is::
condition = 'col1 == b"AAAA"'
.. versionchanged:: 3.0
The start, stop and step parameters now behave like in slice.
"""
return self._where(condition, condvars, start, stop, step)
def _where(self, condition, condvars, start=None, stop=None, step=None):
"""Low-level counterpart of `self.where()`."""
if profile:
tref = clock()
if profile:
show_stats("Entering table._where", tref)
# Adjust the slice to be used.
(start, stop, step) = self._process_range_read(start, stop, step)
if start >= stop: # empty range, reset conditions
self._use_index = False
self._where_condition = None
return iter([])
# Compile the condition and extract usable index conditions.
condvars = self._required_expr_vars(condition, condvars, depth=3)
compiled = self._compile_condition(condition, condvars)
# Can we use indexes?
if compiled.index_expressions:
chunkmap = _table__where_indexed(
self, compiled, condition, condvars, start, stop, step)
if not isinstance(chunkmap, np.ndarray):
# If it is not a NumPy array it should be an iterator
# Reset conditions
self._use_index = False
self._where_condition = None
# ...and return the iterator
return chunkmap
else:
chunkmap = None # default to an in-kernel query
args = [condvars[param] for param in compiled.parameters]
self._where_condition = (compiled.function, args, compiled.kwargs)
row = tableextension.Row(self)
if profile:
show_stats("Exiting table._where", tref)
return row._iter(start, stop, step, chunkmap=chunkmap)
def read_where(self, condition, condvars=None, field=None,
start=None, stop=None, step=None):
"""Read table data fulfilling the given *condition*.
This method is similar to :meth:`Table.read`, having their common
arguments and return values the same meanings. However, only the rows
fulfilling the *condition* are included in the result.
The meaning of the other arguments is the same as in the
:meth:`Table.where` method.
"""
self._g_check_open()
coords = [p.nrow for p in
self._where(condition, condvars, start, stop, step)]
self._where_condition = None # reset the conditions
if len(coords) > 1:
cstart, cstop = coords[0], coords[-1] + 1
if cstop - cstart == len(coords):
# Chances for monotonically increasing row values. Refine.
inc_seq = np.all(np.arange(cstart, cstop) == np.array(coords))
if inc_seq:
return self.read(cstart, cstop, field=field)
return self.read_coordinates(coords, field)
def append_where(self, dstTable, condition=None, condvars=None,
start=None, stop=None, step=None):
"""Append rows fulfilling the condition to the dstTable table.
dstTable must be capable of taking the rows resulting from the query,
i.e. it must have columns with the expected names and compatible
types. The meaning of the other arguments is the same as in the
:meth:`Table.where` method.
The number of rows appended to dstTable is returned as a result.
.. versionchanged:: 3.0
The *whereAppend* method has been renamed into *append_where*.
"""
self._g_check_open()
# Check that the destination file is not in read-only mode.
dstTable._v_file._check_writable()
# Row objects do not support nested columns, so we must iterate
# over the flat column paths. When rows support nesting,
# ``self.colnames`` can be directly iterated upon.
colNames = [colName for colName in self.colpathnames]
dstRow = dstTable.row
nrows = 0
if condition is not None:
srcRows = self._where(condition, condvars, start, stop, step)
else:
srcRows = self.iterrows(start, stop, step)
for srcRow in srcRows:
for colName in colNames:
dstRow[colName] = srcRow[colName]
dstRow.append()
nrows += 1
dstTable.flush()
return nrows
def get_where_list(self, condition, condvars=None, sort=False,
start=None, stop=None, step=None):
"""Get the row coordinates fulfilling the given condition.
The coordinates are returned as a list of the current flavor. sort
means that you want to retrieve the coordinates ordered. The default is
to not sort them.
The meaning of the other arguments is the same as in the
:meth:`Table.where` method.
"""
self._g_check_open()
coords = [p.nrow for p in
self._where(condition, condvars, start, stop, step)]
coords = np.array(coords, dtype=SizeType)
# Reset the conditions
self._where_condition = None
if sort:
coords = np.sort(coords)
return internal_to_flavor(coords, self.flavor)
def itersequence(self, sequence):
"""Iterate over a sequence of row coordinates."""
if not hasattr(sequence, '__getitem__'):
raise TypeError("Wrong 'sequence' parameter type. Only sequences "
"are suported.")
# start, stop and step are necessary for the new iterator for
# coordinates, and perhaps it would be useful to add them as
# parameters in the future (not now, because I've just removed
# the `sort` argument for 2.1).
#
# *Important note*: Negative values for step are not supported
# for the general case, but only for the itersorted() and
# read_sorted() purposes! The self._process_range_read will raise
# an appropiate error.
# F. Alted 2008-09-18
# A.V. 20130513: _process_range_read --> _process_range
(start, stop, step) = self._process_range(None, None, None)
if (start > stop) or (len(sequence) == 0):
return iter([])
row = tableextension.Row(self)
return row._iter(start, stop, step, coords=sequence)
def _check_sortby_csi(self, sortby, checkCSI):
if isinstance(sortby, Column):
icol = sortby
elif isinstance(sortby, str):
icol = self.cols._f_col(sortby)
else:
raise TypeError(
"`sortby` can only be a `Column` or string object, "
"but you passed an object of type: %s" % type(sortby))
if icol.is_indexed and icol.index.kind == "full":
if checkCSI and not icol.index.is_csi:
# The index exists, but it is not a CSI one.
raise ValueError(
"Field `%s` must have associated a CSI index "
"in table `%s`, but the existing one is not. "
% (sortby, self))
return icol.index
else:
raise ValueError(
"Field `%s` must have associated a 'full' index "
"in table `%s`." % (sortby, self))
def itersorted(self, sortby, checkCSI=False,
start=None, stop=None, step=None):
"""Iterate table data following the order of the index of sortby
column.
The sortby column must have associated a full index. If you want to
ensure a fully sorted order, the index must be a CSI one. You may want
to use the checkCSI argument in order to explicitly check for the
existence of a CSI index.
The meaning of the start, stop and step arguments is the same as in
:meth:`Table.read`.
.. versionchanged:: 3.0
If the *start* parameter is provided and *stop* is None then the
table is iterated from *start* to the last line.
In PyTables < 3.0 only one element was returned.
"""
index = self._check_sortby_csi(sortby, checkCSI)
# Adjust the slice to be used.
(start, stop, step) = self._process_range(start, stop, step,
warn_negstep=False)
if (start > stop and 0 < step) or (start < stop and 0 > step):
# Fall-back action is to return an empty iterator
return iter([])
row = tableextension.Row(self)
return row._iter(start, stop, step, coords=index)
def read_sorted(self, sortby, checkCSI=False, field=None,
start=None, stop=None, step=None):
"""Read table data following the order of the index of sortby column.
The sortby column must have associated a full index. If you want to
ensure a fully sorted order, the index must be a CSI one. You may want
to use the checkCSI argument in order to explicitly check for the
existence of a CSI index.
If field is supplied only the named column will be selected. If the
column is not nested, an *array* of the current flavor will be
returned; if it is, a *structured array* will be used instead. If no
field is specified, all the columns will be returned in a structured
array of the current flavor.
The meaning of the start, stop and step arguments is the same as in
:meth:`Table.read`.
.. versionchanged:: 3.0
The start, stop and step parameters now behave like in slice.
"""
self._g_check_open()
index = self._check_sortby_csi(sortby, checkCSI)
coords = index[start:stop:step]
return self.read_coordinates(coords, field)
def iterrows(self, start=None, stop=None, step=None):
"""Iterate over the table using a Row instance.
If a range is not supplied, *all the rows* in the table are iterated
upon - you can also use the :meth:`Table.__iter__` special method for
that purpose. If you want to iterate over a given *range of rows* in
the table, you may use the start, stop and step parameters.
.. warning::
When in the middle of a table row iterator, you should not
use methods that can change the number of rows in the table
(like :meth:`Table.append` or :meth:`Table.remove_rows`) or
unexpected errors will happen.
See Also
--------
tableextension.Row : the table row iterator and field accessor
Examples
--------
::
result = [ row['var2'] for row in table.iterrows(step=5)
if row['var1'] <= 20 ]
.. versionchanged:: 3.0
If the *start* parameter is provided and *stop* is None then the
table is iterated from *start* to the last line.
In PyTables < 3.0 only one element was returned.
"""
(start, stop, step) = self._process_range(start, stop, step,
warn_negstep=False)
if (start > stop and 0 < step) or (start < stop and 0 > step):
# Fall-back action is to return an empty iterator
return iter([])
row = tableextension.Row(self)
return row._iter(start, stop, step)
def __iter__(self):
"""Iterate over the table using a Row instance.
This is equivalent to calling :meth:`Table.iterrows` with default
arguments, i.e. it iterates over *all the rows* in the table.
See Also
--------
tableextension.Row : the table row iterator and field accessor
Examples
--------
::
result = [ row['var2'] for row in table if row['var1'] <= 20 ]
Which is equivalent to::
result = [ row['var2'] for row in table.iterrows()
if row['var1'] <= 20 ]
"""
return self.iterrows()
def _read(self, start, stop, step, field=None, out=None):
"""Read a range of rows and return an in-memory object."""
select_field = None
if field:
if field not in self.coldtypes:
if field in self.description._v_names:
# Remember to select this field
select_field = field
field = None
else:
raise KeyError(("Field {} not found in table "
"{}").format(field, self))
else:
# The column hangs directly from the top
dtype_field = self.coldtypes[field]
# Return a rank-0 array if start > stop
if (start >= stop and 0 < step) or (start <= stop and 0 > step):
if field is None:
nra = self._get_container(0)
return nra
return np.empty(shape=0, dtype=dtype_field)
nrows = len(range(start, stop, step))
if out is None:
# Compute the shape of the resulting column object
if field:
# Create a container for the results
result = np.empty(shape=nrows, dtype=dtype_field)
else:
# Recarray case
result = self._get_container(nrows)
else:
# there is no fast way to byteswap, since different columns may
# have different byteorders
if not out.dtype.isnative:
raise ValueError("output array must be in system's byteorder "
"or results will be incorrect")
if field:
bytes_required = dtype_field.itemsize * nrows
else:
bytes_required = self.rowsize * nrows
if bytes_required != out.nbytes:
raise ValueError(f'output array size invalid, got {out.nbytes}'
f' bytes, need {bytes_required} bytes')
if not out.flags['C_CONTIGUOUS']:
raise ValueError('output array not C contiguous')
result = out
# Call the routine to fill-up the resulting array
if step == 1 and not field:
# This optimization works three times faster than
# the row._fill_col method (up to 170 MB/s on a pentium IV @ 2GHz)
self._read_records(start, stop - start, result)
# Warning!: _read_field_name should not be used until
# H5TBread_fields_name in tableextension will be finished
# F. Alted 2005/05/26
# XYX Ho implementem per a PyTables 2.0??
elif field and step > 15 and 0:
# For step>15, this seems to work always faster than row._fill_col.
self._read_field_name(result, start, stop, step, field)
else:
self.row._fill_col(result, start, stop, step, field)
if select_field:
return result[select_field]
else:
return result
def read(self, start=None, stop=None, step=None, field=None, out=None):
"""Get data in the table as a (record) array.
The start, stop and step parameters can be used to select only
a *range of rows* in the table. Their meanings are the same as
in the built-in Python slices.
If field is supplied only the named column will be selected.
If the column is not nested, an *array* of the current flavor
will be returned; if it is, a *structured array* will be used
instead. If no field is specified, all the columns will be
returned in a structured array of the current flavor.
Columns under a nested column can be specified in the field
parameter by using a slash character (/) as a separator (e.g.
'position/x').
The out parameter may be used to specify a NumPy array to
receive the output data. Note that the array must have the
same size as the data selected with the other parameters.
Note that the array's datatype is not checked and no type
casting is performed, so if it does not match the datatype on
disk, the output will not be correct.
When specifying a single nested column with the field parameter,
and supplying an output buffer with the out parameter, the
output buffer must contain all columns in the table.
The data in all columns will be read into the output buffer.
However, only the specified nested column will be returned from
the method call.
When data is read from disk in NumPy format, the output will be
in the current system's byteorder, regardless of how it is
stored on disk. If the out parameter is specified, the output
array also must be in the current system's byteorder.
.. versionchanged:: 3.0
Added the *out* parameter. Also the start, stop and step
parameters now behave like in slice.
Examples
--------
Reading the entire table::
t.read()
Reading record n. 6::
t.read(6, 7)
Reading from record n. 6 to the end of the table::
t.read(6)
"""
self._g_check_open()
if field:
self._check_column(field)
if out is not None and self.flavor != 'numpy':
msg = ("Optional 'out' argument may only be supplied if array "
"flavor is 'numpy', currently is {}").format(self.flavor)
raise TypeError(msg)
start, stop, step = self._process_range(start, stop, step,
warn_negstep=False)
arr = self._read(start, stop, step, field, out)
return internal_to_flavor(arr, self.flavor)
def _read_coordinates(self, coords, field=None):
"""Private part of `read_coordinates()` with no flavor conversion."""
coords = self._point_selection(coords)
ncoords = len(coords)
# Create a read buffer only if needed
if field is None or ncoords > 0:
# Doing a copy is faster when ncoords is small (<1000)
if ncoords < min(1000, self.nrowsinbuf):
result = self._v_iobuf[:ncoords].copy()
else:
result = self._get_container(ncoords)
# Do the real read
if ncoords > 0:
# Turn coords into an array of coordinate indexes, if necessary
if not (isinstance(coords, np.ndarray) and
coords.dtype.type is _npsizetype and
coords.flags.contiguous and
coords.flags.aligned):
# Get a contiguous and aligned coordinate array
coords = np.array(coords, dtype=SizeType)
self._read_elements(coords, result)
# Do the final conversions, if needed
if field:
if ncoords > 0:
result = get_nested_field(result, field)
else:
# Get an empty array from the cache
result = self._getemptyarray(self.coldtypes[field])
return result
def read_coordinates(self, coords, field=None):
"""Get a set of rows given their indexes as a (record) array.
This method works much like the :meth:`Table.read` method, but it uses
a sequence (coords) of row indexes to select the wanted columns,
instead of a column range.
The selected rows are returned in an array or structured array of the
current flavor.
"""
self._g_check_open()
result = self._read_coordinates(coords, field)
return internal_to_flavor(result, self.flavor)
def get_enum(self, colname):
"""Get the enumerated type associated with the named column.
If the column named colname (a string) exists and is of an enumerated
type, the corresponding Enum instance (see :ref:`EnumClassDescr`) is
returned. If it is not of an enumerated type, a TypeError is raised. If
the column does not exist, a KeyError is raised.
"""
self._check_column(colname)
try:
return self._colenums[colname]
except KeyError:
raise TypeError(
"column ``%s`` of table ``%s`` is not of an enumerated type"
% (colname, self._v_pathname))
def col(self, name):
"""Get a column from the table.
If a column called name exists in the table, it is read and returned as
a NumPy object. If it does not exist, a KeyError is raised.
Examples
--------
::
narray = table.col('var2')
That statement is equivalent to::
narray = table.read(field='var2')
Here you can see how this method can be used as a shorthand for the
:meth:`Table.read` method.
"""
return self.read(field=name)
def __getitem__(self, key):
"""Get a row or a range of rows from the table.
If key argument is an integer, the corresponding table row is returned
as a record of the current flavor. If key is a slice, the range of rows
determined by it is returned as a structured array of the current
flavor.
In addition, NumPy-style point selections are supported. In
particular, if key is a list of row coordinates, the set of rows
determined by it is returned. Furthermore, if key is an array of
boolean values, only the coordinates where key is True are returned.
Note that for the latter to work it is necessary that key list would
contain exactly as many rows as the table has.
Examples
--------
::
record = table[4]
recarray = table[4:1000:2]
recarray = table[[4,1000]] # only retrieves rows 4 and 1000
recarray = table[[True, False, ..., True]]
Those statements are equivalent to::
record = table.read(start=4)[0]
recarray = table.read(start=4, stop=1000, step=2)
recarray = table.read_coordinates([4,1000])
recarray = table.read_coordinates([True, False, ..., True])
Here, you can see how indexing can be used as a shorthand for the
:meth:`Table.read` and :meth:`Table.read_coordinates` methods.
"""
self._g_check_open()
if is_idx(key):
key = operator.index(key)
# Index out of range protection
if key >= self.nrows:
raise IndexError("Index out of range")
if key < 0:
# To support negative values
key += self.nrows
(start, stop, step) = self._process_range(key, key + 1, 1)
return self.read(start, stop, step)[0]
elif isinstance(key, slice):
(start, stop, step) = self._process_range(
key.start, key.stop, key.step)
return self.read(start, stop, step)
# Try with a boolean or point selection
elif type(key) in (list, tuple) or isinstance(key, np.ndarray):
return self._read_coordinates(key, None)
else:
raise IndexError(f"Invalid index or slice: {key!r}")
def __setitem__(self, key, value):
"""Set a row or a range of rows in the table.
It takes different actions depending on the type of the *key*
parameter: if it is an integer, the corresponding table row is
set to *value* (a record or sequence capable of being converted
to the table structure). If *key* is a slice, the row slice
determined by it is set to *value* (a record array or sequence
capable of being converted to the table structure).
In addition, NumPy-style point selections are supported. In
particular, if key is a list of row coordinates, the set of rows
determined by it is set to value. Furthermore, if key is an array of
boolean values, only the coordinates where key is True are set to
values from value. Note that for the latter to work it is necessary
that key list would contain exactly as many rows as the table has.
Examples
--------
::
# Modify just one existing row
table[2] = [456,'db2',1.2]
# Modify two existing rows
rows = np.rec.array(
[[457,'db1',1.2],[6,'de2',1.3]], formats='i4,S3,f8'
)
table[1:30:2] = rows # modify a table slice
table[[1,3]] = rows # only modifies rows 1 and 3
table[[True,False,True]] = rows # only modifies rows 0 and 2
Which is equivalent to::
table.modify_rows(start=2, rows=[456,'db2',1.2])
rows = np.rec.array(
[[457,'db1',1.2],[6,'de2',1.3]], formats='i4,S3,f8'
)
table.modify_rows(start=1, stop=3, step=2, rows=rows)
table.modify_coordinates([1,3,2], rows)
table.modify_coordinates([True, False, True], rows)
Here, you can see how indexing can be used as a shorthand for the
:meth:`Table.modify_rows` and :meth:`Table.modify_coordinates`
methods.
"""
self._g_check_open()
self._v_file._check_writable()
if is_idx(key):
key = operator.index(key)
# Index out of range protection
if key >= self.nrows:
raise IndexError("Index out of range")
if key < 0:
# To support negative values
key += self.nrows
return self.modify_rows(key, key + 1, 1, [value])
elif isinstance(key, slice):
(start, stop, step) = self._process_range(
key.start, key.stop, key.step)
return self.modify_rows(start, stop, step, value)
# Try with a boolean or point selection
elif type(key) in (list, tuple) or isinstance(key, np.ndarray):
return self.modify_coordinates(key, value)
else:
raise IndexError(f"Invalid index or slice: {key!r}")
def _save_buffered_rows(self, wbufRA, lenrows):
"""Update the indexes after a flushing of rows."""
self._open_append(wbufRA)
self._append_records(lenrows)
self._close_append()
if self.indexed:
self._unsaved_indexedrows += lenrows
# The table caches for indexed queries are dirty now
self._dirtycache = True
if self.autoindex:
# Flush the unindexed rows
self.flush_rows_to_index(_lastrow=False)
else:
# All the columns are dirty now
self._mark_columns_as_dirty(self.colpathnames)
def append(self, rows):
"""Append a sequence of rows to the end of the table.
The rows argument may be any object which can be converted to
a structured array compliant with the table structure
(otherwise, a ValueError is raised). This includes NumPy
structured arrays, lists of tuples or array records, and a
string or Python buffer.
Examples
--------
::
import tables as tb
class Particle(tb.IsDescription):
name = tb.StringCol(16, pos=1) # 16-character String
lati = tb.IntCol(pos=2) # integer
longi = tb.IntCol(pos=3) # integer
pressure = tb.Float32Col(pos=4) # float (single-precision)
temperature = tb.FloatCol(pos=5) # double (double-precision)
fileh = tb.open_file('test4.h5', mode='w')
table = fileh.create_table(fileh.root, 'table', Particle,
"A table")
# Append several rows in only one call
table.append([("Particle: 10", 10, 0, 10 * 10, 10**2),
("Particle: 11", 11, -1, 11 * 11, 11**2),
("Particle: 12", 12, -2, 12 * 12, 12**2)])
fileh.close()
"""
self._g_check_open()
self._v_file._check_writable()
if not self._chunked:
raise HDF5ExtError(
"You cannot append rows to a non-chunked table.", h5bt=False)
if (hasattr(rows, "dtype") and
not self.description._v_is_nested and
rows.dtype == self.dtype):
# Shortcut for compliant arrays
# (for some reason, not valid for nested types)
wbufRA = rows
else:
# Try to convert the object into a recarray compliant with table
try:
iflavor = flavor_of(rows)
if iflavor != 'python':
rows = array_as_internal(rows, iflavor)
# Works for Python structures and always copies the original,
# so the resulting object is safe for in-place conversion.
wbufRA = np.rec.array(rows, dtype=self._v_dtype)
except Exception as exc: # XXX
raise ValueError("rows parameter cannot be converted into a "
"recarray object compliant with table '%s'. "
"The error was: <%s>" % (str(self), exc))
lenrows = wbufRA.shape[0]
# If the number of rows to append is zero, don't do anything else
if lenrows > 0:
# Save write buffer to disk
self._save_buffered_rows(wbufRA, lenrows)
def _conv_to_recarr(self, obj):
"""Try to convert the object into a recarray."""
try:
iflavor = flavor_of(obj)
if iflavor != 'python':
obj = array_as_internal(obj, iflavor)
if hasattr(obj, "shape") and obj.shape == ():
# To allow conversion of scalars (void type) into arrays.
# See http://projects.scipy.org/scipy/numpy/ticket/315
# for discussion on how to pass buffers to constructors
# See also http://projects.scipy.org/scipy/numpy/ticket/348
recarr = np.array([obj], dtype=self._v_dtype)
else:
# Works for Python structures and always copies the original,
# so the resulting object is safe for in-place conversion.
recarr = np.rec.array(obj, dtype=self._v_dtype)
except Exception as exc: # XXX
raise ValueError("Object cannot be converted into a recarray "
"object compliant with table format '%s'. "
"The error was: <%s>" %
(self.description._v_nested_descr, exc))
return recarr
def modify_coordinates(self, coords, rows):
"""Modify a series of rows in positions specified in coords.
The values in the selected rows will be modified with the data given in
rows. This method returns the number of rows modified.
The possible values for the rows argument are the same as in
:meth:`Table.append`.
"""
if rows is None: # Nothing to be done
return SizeType(0)
# Convert the coordinates to something expected by HDF5
coords = self._point_selection(coords)
lcoords = len(coords)
if len(rows) < lcoords:
raise ValueError("The value has not enough elements to fill-in "
"the specified range")
# Convert rows into a recarray
recarr = self._conv_to_recarr(rows)
if len(coords) > 0:
# Do the actual update of rows
self._update_elements(lcoords, coords, recarr)
# Redo the index if needed
self._reindex(self.colpathnames)
return SizeType(lcoords)
def modify_rows(self, start=None, stop=None, step=None, rows=None):
"""Modify a series of rows in the slice [start:stop:step].
The values in the selected rows will be modified with the data given in
rows. This method returns the number of rows modified. Should the
modification exceed the length of the table, an IndexError is raised
before changing data.
The possible values for the rows argument are the same as in
:meth:`Table.append`.
"""
if step is None:
step = 1
if rows is None: # Nothing to be done
return SizeType(0)
if start is None:
start = 0
if start < 0:
raise ValueError("'start' must have a positive value.")
if step < 1:
raise ValueError(
"'step' must have a value greater or equal than 1.")
if stop is None:
# compute the stop value. start + len(rows)*step does not work
stop = start + (len(rows) - 1) * step + 1
(start, stop, step) = self._process_range(start, stop, step)
if stop > self.nrows:
raise IndexError("This modification will exceed the length of "
"the table. Giving up.")
# Compute the number of rows to read.
nrows = len(range(start, stop, step))
if len(rows) != nrows:
raise ValueError("The value has different elements than the "
"specified range")
# Convert rows into a recarray
recarr = self._conv_to_recarr(rows)
lenrows = len(recarr)
if start + lenrows > self.nrows:
raise IndexError("This modification will exceed the length of the "
"table. Giving up.")
# Do the actual update
self._update_records(start, stop, step, recarr)
# Redo the index if needed
self._reindex(self.colpathnames)
return SizeType(lenrows)
def modify_column(self, start=None, stop=None, step=None,
column=None, colname=None):
"""Modify one single column in the row slice [start:stop:step].
The colname argument specifies the name of the column in the
table to be modified with the data given in column. This
method returns the number of rows modified. Should the
modification exceed the length of the table, an IndexError is
raised before changing data.
The *column* argument may be any object which can be converted
to a (record) array compliant with the structure of the column
to be modified (otherwise, a ValueError is raised). This
includes NumPy (record) arrays, lists of scalars, tuples or
array records, and a string or Python buffer.
"""
if step is None:
step = 1
if not isinstance(colname, str):
raise TypeError("The 'colname' parameter must be a string.")
self._v_file._check_writable()
if column is None: # Nothing to be done
return SizeType(0)
if start is None:
start = 0
if start < 0:
raise ValueError("'start' must have a positive value.")
if step < 1:
raise ValueError(
"'step' must have a value greater or equal than 1.")
# Get the column format to be modified:
objcol = self._get_column_instance(colname)
descr = [objcol._v_parent._v_nested_descr[objcol._v_pos]]
# Try to convert the column object into a NumPy ndarray
try:
# If the column is a recarray (or kind of), convert into ndarray
if hasattr(column, 'dtype') and column.dtype.kind == 'V':
column = np.rec.array(column, dtype=descr).field(0)
else:
# Make sure the result is always a *copy* of the original,
# so the resulting object is safe for in-place conversion.
iflavor = flavor_of(column)
column = array_as_internal(column, iflavor)
except Exception as exc: # XXX
raise ValueError("column parameter cannot be converted into a "
"ndarray object compliant with specified column "
"'%s'. The error was: <%s>" % (str(column), exc))
# Get rid of single-dimensional dimensions
column = column.squeeze()
if column.shape == ():
# Oops, stripped off to much dimensions
column.shape = (1,)
if stop is None:
# compute the stop value. start + len(rows)*step does not work
stop = start + (len(column) - 1) * step + 1
(start, stop, step) = self._process_range(start, stop, step)
if stop > self.nrows:
raise IndexError("This modification will exceed the length of "
"the table. Giving up.")
# Compute the number of rows to read.
nrows = len(range(start, stop, step))
if len(column) < nrows:
raise ValueError("The value has not enough elements to fill-in "
"the specified range")
# Now, read the original values:
mod_recarr = self._read(start, stop, step)
# Modify the appropriate column in the original recarray
mod_col = get_nested_field(mod_recarr, colname)
mod_col[:] = column
# save this modified rows in table
self._update_records(start, stop, step, mod_recarr)
# Redo the index if needed
self._reindex([colname])
return SizeType(nrows)
def modify_columns(self, start=None, stop=None, step=None,
columns=None, names=None):
"""Modify a series of columns in the row slice [start:stop:step].
The names argument specifies the names of the columns in the
table to be modified with the data given in columns. This
method returns the number of rows modified. Should the
modification exceed the length of the table, an IndexError
is raised before changing data.
The columns argument may be any object which can be converted
to a structured array compliant with the structure of the
columns to be modified (otherwise, a ValueError is raised).
This includes NumPy structured arrays, lists of tuples or array
records, and a string or Python buffer.
"""
if step is None:
step = 1
if type(names) not in (list, tuple):
raise TypeError("The 'names' parameter must be a list of strings.")
if columns is None: # Nothing to be done
return SizeType(0)
if start is None:
start = 0
if start < 0:
raise ValueError("'start' must have a positive value.")
if step < 1:
raise ValueError("'step' must have a value greater or "
"equal than 1.")
descr = []
for colname in names:
objcol = self._get_column_instance(colname)
descr.append(objcol._v_parent._v_nested_descr[objcol._v_pos])
# descr.append(objcol._v_parent._v_dtype[objcol._v_pos])
# Try to convert the columns object into a recarray
try:
# Make sure the result is always a *copy* of the original,
# so the resulting object is safe for in-place conversion.
iflavor = flavor_of(columns)
if iflavor != 'python':
columns = array_as_internal(columns, iflavor)
recarray = np.rec.array(columns, dtype=descr)
else:
recarray = np.rec.fromarrays(columns, dtype=descr)
except Exception as exc: # XXX
raise ValueError("columns parameter cannot be converted into a "
"recarray object compliant with table '%s'. "
"The error was: <%s>" % (str(self), exc))
if stop is None:
# compute the stop value. start + len(rows)*step does not work
stop = start + (len(recarray) - 1) * step + 1
(start, stop, step) = self._process_range(start, stop, step)
if stop > self.nrows:
raise IndexError("This modification will exceed the length of "
"the table. Giving up.")
# Compute the number of rows to read.
nrows = len(range(start, stop, step))
if len(recarray) < nrows:
raise ValueError("The value has not enough elements to fill-in "
"the specified range")
# Now, read the original values:
mod_recarr = self._read(start, stop, step)
# Modify the appropriate columns in the original recarray
for i, name in enumerate(recarray.dtype.names):
mod_col = get_nested_field(mod_recarr, names[i])
mod_col[:] = recarray[name].squeeze()
# save this modified rows in table
self._update_records(start, stop, step, mod_recarr)
# Redo the index if needed
self._reindex(names)
return SizeType(nrows)
def flush_rows_to_index(self, _lastrow=True):
"""Add remaining rows in buffers to non-dirty indexes.
This can be useful when you have chosen non-automatic indexing
for the table (see the :attr:`Table.autoindex` property in
:class:`Table`) and you want to update the indexes on it.
"""
rowsadded = 0
if self.indexed:
# Update the number of unsaved indexed rows
start = self._indexedrows
nrows = self._unsaved_indexedrows
for (colname, colindexed) in self.colindexed.items():
if colindexed:
col = self.cols._g_col(colname)
if nrows > 0 and not col.index.dirty:
rowsadded = self._add_rows_to_index(
colname, start, nrows, _lastrow, update=True)
self._unsaved_indexedrows -= rowsadded
self._indexedrows += rowsadded
return rowsadded
def _add_rows_to_index(self, colname, start, nrows, lastrow, update):
"""Add more elements to the existing index."""
# This method really belongs to Column, but since it makes extensive
# use of the table, it gets dangerous when closing the file, since the
# column may be accessing a table which is being destroyed.
index = self.cols._g_col(colname).index
slicesize = index.slicesize
# The next loop does not rely on xrange so that it can
# deal with long ints (i.e. more than 32-bit integers)
# This allows to index columns with more than 2**31 rows
# F. Alted 2005-05-09
startLR = index.sorted.nrows * slicesize
indexedrows = startLR - start
stop = start + nrows - slicesize + 1
while startLR < stop:
index.append(
[self._read(startLR, startLR + slicesize, 1, colname)],
update=update)
indexedrows += slicesize
startLR += slicesize
# index the remaining rows in last row
if lastrow and startLR < self.nrows:
index.append_last_row(
[self._read(startLR, self.nrows, 1, colname)],
update=update)
indexedrows += self.nrows - startLR
return indexedrows
def remove_rows(self, start=None, stop=None, step=None):
"""Remove a range of rows in the table.
If only start is supplied, that row and all following will be deleted.
If a range is supplied, i.e. both the start and stop parameters are
passed, all the rows in the range are removed.
.. versionchanged:: 3.0
The start, stop and step parameters now behave like in slice.
.. seealso:: remove_row()
Parameters
----------
start : int
Sets the starting row to be removed. It accepts negative values
meaning that the count starts from the end. A value of 0 means the
first row.
stop : int
Sets the last row to be removed to stop-1, i.e. the end point is
omitted (in the Python range() tradition). Negative values are also
accepted. If None all rows after start will be removed.
step : int
The step size between rows to remove.
.. versionadded:: 3.0
Examples
--------
Removing rows from 5 to 10 (excluded)::
t.remove_rows(5, 10)
Removing all rows starting from the 10th::
t.remove_rows(10)
Removing the 6th row::
t.remove_rows(6, 7)
.. note::
removing a single row can be done using the specific
:meth:`remove_row` method.
"""
(start, stop, step) = self._process_range(start, stop, step)
nrows = self._remove_rows(start, stop, step)
# remove_rows is a invalidating index operation
self._reindex(self.colpathnames)
return SizeType(nrows)
def remove_row(self, n):
"""Removes a row from the table.
Parameters
----------
n : int
The index of the row to remove.
.. versionadded:: 3.0
Examples
--------
Remove row 15::
table.remove_row(15)
Which is equivalent to::
table.remove_rows(15, 16)
.. warning::
This is not equivalent to::
table.remove_rows(15)
"""
self.remove_rows(start=n, stop=n + 1)
def _g_update_dependent(self):
super()._g_update_dependent()
# Update the new path in columns
self.cols._g_update_table_location(self)
# Update the new path in the Row instance, if cached. Fixes #224.
if 'row' in self.__dict__:
self.__dict__['row'] = tableextension.Row(self)
def _g_move(self, newparent, newname):
"""Move this node in the hierarchy.
This overloads the Node._g_move() method.
"""
itgpathname = _index_pathname_of(self)
# First, move the table to the new location.
super()._g_move(newparent, newname)
# Then move the associated index group (if any).
try:
itgroup = self._v_file._get_node(itgpathname)
except NoSuchNodeError:
pass
else:
newigroup = self._v_parent
newiname = _index_name_of(self)
itgroup._g_move(newigroup, newiname)
def _g_remove(self, recursive=False, force=False):
# Remove the associated index group (if any).
itgpathname = _index_pathname_of(self)
try:
itgroup = self._v_file._get_node(itgpathname)
except NoSuchNodeError:
pass
else:
itgroup._f_remove(recursive=True)
self.indexed = False # there are indexes no more
# Remove the leaf itself from the hierarchy.
super()._g_remove(recursive, force)
def _set_column_indexing(self, colpathname, indexed):
"""Mark the referred column as indexed or non-indexed."""
colindexed = self.colindexed
isindexed, wasindexed = bool(indexed), colindexed[colpathname]
if isindexed == wasindexed:
return # indexing state is unchanged
# Changing the set of indexed columns invalidates the condition cache
self._condition_cache.clear()
colindexed[colpathname] = isindexed
self.indexed = max(colindexed.values()) # this is an OR :)
def _mark_columns_as_dirty(self, colnames):
"""Mark column indexes in `colnames` as dirty."""
assert len(colnames) > 0
if self.indexed:
colindexed, cols = self.colindexed, self.cols
# Mark the proper indexes as dirty
for colname in colnames:
if colindexed[colname]:
col = cols._g_col(colname)
col.index.dirty = True
def _reindex(self, colnames):
"""Re-index columns in `colnames` if automatic indexing is true."""
if self.indexed:
colindexed, cols = self.colindexed, self.cols
colstoindex = []
# Mark the proper indexes as dirty
for colname in colnames:
if colindexed[colname]:
col = cols._g_col(colname)
col.index.dirty = True
colstoindex.append(colname)
# Now, re-index the dirty ones
if self.autoindex and colstoindex:
self._do_reindex(dirty=True)
# The table caches for indexed queries are dirty now
self._dirtycache = True
def _do_reindex(self, dirty):
"""Common code for `reindex()` and `reindex_dirty()`."""
indexedrows = 0
for (colname, colindexed) in self.colindexed.items():
if colindexed:
indexcol = self.cols._g_col(colname)
indexedrows = indexcol._do_reindex(dirty)
# Update counters in case some column has been updated
if indexedrows > 0:
self._indexedrows = indexedrows
self._unsaved_indexedrows = self.nrows - indexedrows
return SizeType(indexedrows)
def reindex(self):
"""Recompute all the existing indexes in the table.
This can be useful when you suspect that, for any reason, the
index information for columns is no longer valid and want to
rebuild the indexes on it.
"""
self._do_reindex(dirty=False)
def reindex_dirty(self):
"""Recompute the existing indexes in table, *if* they are dirty.
This can be useful when you have set :attr:`Table.autoindex`
(see :class:`Table`) to false for the table and you want to
update the indexes after a invalidating index operation
(:meth:`Table.remove_rows`, for example).
"""
self._do_reindex(dirty=True)
def _g_copy_rows(self, object, start, stop, step, sortby, checkCSI):
"""Copy rows from self to object"""
if sortby is None:
self._g_copy_rows_optim(object, start, stop, step)
return
lenbuf = self.nrowsinbuf
absstep = step
if step < 0:
absstep = -step
start, stop = stop + 1, start + 1
if sortby is not None:
index = self._check_sortby_csi(sortby, checkCSI)
for start2 in range(start, stop, absstep * lenbuf):
stop2 = start2 + absstep * lenbuf
if stop2 > stop:
stop2 = stop
# The next 'if' is not needed, but it doesn't bother either
if sortby is None:
rows = self[start2:stop2:step]
else:
coords = index[start2:stop2:step]
rows = self.read_coordinates(coords)
# Save the records on disk
object.append(rows)
object.flush()
def _g_copy_rows_optim(self, object, start, stop, step):
"""Copy rows from self to object (optimized version)"""
nrowsinbuf = self.nrowsinbuf
object._open_append(self._v_iobuf)
nrowsdest = object.nrows
for start2 in range(start, stop, step * nrowsinbuf):
# Save the records on disk
stop2 = start2 + step * nrowsinbuf
if stop2 > stop:
stop2 = stop
# Optimized version (it saves some conversions)
nrows = ((stop2 - start2 - 1) // step) + 1
self.row._fill_col(self._v_iobuf, start2, stop2, step, None)
# The output buffer is created anew,
# so the operation is safe to in-place conversion.
object._append_records(nrows)
nrowsdest += nrows
object._close_append()
def _g_prop_indexes(self, other):
"""Generate index in `other` table for every indexed column here."""
oldcols, newcols = self.colinstances, other.colinstances
for colname in newcols:
if (isinstance(oldcols[colname], Column)):
oldcolindexed = oldcols[colname].is_indexed
if oldcolindexed:
oldcolindex = oldcols[colname].index
newcol = newcols[colname]
newcol.create_index(
kind=oldcolindex.kind, optlevel=oldcolindex.optlevel,
filters=oldcolindex.filters, tmp_dir=None)
def _g_copy_with_stats(self, group, name, start, stop, step,
title, filters, chunkshape, _log, **kwargs):
"""Private part of Leaf.copy() for each kind of leaf."""
# Get the private args for the Table flavor of copy()
sortby = kwargs.pop('sortby', None)
propindexes = kwargs.pop('propindexes', False)
checkCSI = kwargs.pop('checkCSI', False)
# Compute the correct indices.
(start, stop, step) = self._process_range_read(
start, stop, step, warn_negstep=sortby is None)
# And the number of final rows
nrows = len(range(start, stop, step))
# Create the new table and copy the selected data.
newtable = Table(group, name, self.description, title=title,
filters=filters, expectedrows=nrows,
chunkshape=chunkshape,
_log=_log)
self._g_copy_rows(newtable, start, stop, step, sortby, checkCSI)
nbytes = newtable.nrows * newtable.rowsize
# Generate equivalent indexes in the new table, if required.
if propindexes and self.indexed:
self._g_prop_indexes(newtable)
return (newtable, nbytes)
# This overloading of copy is needed here in order to document
# the additional keywords for the Table case.
def copy(self, newparent=None, newname=None, overwrite=False,
createparents=False, **kwargs):
"""Copy this table and return the new one.
This method has the behavior and keywords described in
:meth:`Leaf.copy`. Moreover, it recognises the following additional
keyword arguments.
Parameters
----------
sortby
If specified, and sortby corresponds to a column with an index,
then the copy will be sorted by this index. If you want to ensure
a fully sorted order, the index must be a CSI one. A reverse
sorted copy can be achieved by specifying a negative value for the
step keyword. If sortby is omitted or None, the original table
order is used.
checkCSI
If true and a CSI index does not exist for the sortby column, an
error will be raised. If false (the default), it does nothing.
You can use this flag in order to explicitly check for the
existence of a CSI index.
propindexes
If true, the existing indexes in the source table are propagated
(created) to the new one. If false (the default), the indexes are
not propagated.
"""
return super().copy(
newparent, newname, overwrite, createparents, **kwargs)
def flush(self):
"""Flush the table buffers."""
if self._v_file._iswritable():
# Flush rows that remains to be appended
if 'row' in self.__dict__:
self.row._flush_buffered_rows()
if self.indexed and self.autoindex:
# Flush any unindexed row
rowsadded = self.flush_rows_to_index(_lastrow=True)
assert rowsadded <= 0 or self._indexedrows == self.nrows, \
("internal error: the number of indexed rows (%d) "
"and rows in the table (%d) is not equal; "
"please report this to the authors."
% (self._indexedrows, self.nrows))
if self._dirtyindexes:
# Finally, re-index any dirty column
self.reindex_dirty()
super().flush()
def _g_pre_kill_hook(self):
"""Code to be called before killing the node."""
# Flush the buffers before to clean-up them
# self.flush()
# It seems that flushing during the __del__ phase is a sure receipt for
# bringing all kind of problems:
# 1. Illegal Instruction
# 2. Malloc(): trying to call free() twice
# 3. Bus Error
# 4. Segmentation fault
# So, the best would be doing *nothing* at all in this __del__ phase.
# As a consequence, the I/O will not be cleaned until a call to
# Table.flush() would be done. This could lead to a potentially large
# memory consumption.
# NOTE: The user should make a call to Table.flush() whenever he has
# finished working with his table.
# I've added a Performance warning in order to compel the user to
# call self.flush() before the table is being preempted.
# F. Alted 2006-08-03
if (('row' in self.__dict__ and self.row._get_unsaved_nrows() > 0) or
(self.indexed and self.autoindex and
(self._unsaved_indexedrows > 0 or self._dirtyindexes))):
warnings.warn(("table ``%s`` is being preempted from alive nodes "
"without its buffers being flushed or with some "
"index being dirty. This may lead to very "
"ineficient use of resources and even to fatal "
"errors in certain situations. Please do a call "
"to the .flush() or .reindex_dirty() methods on "
"this table before start using other nodes.")
% (self._v_pathname), PerformanceWarning)
# Get rid of the IO buffers (if they have been created at all)
mydict = self.__dict__
if '_v_iobuf' in mydict:
del mydict['_v_iobuf']
if '_v_wdflts' in mydict:
del mydict['_v_wdflts']
def _f_close(self, flush=True):
if not self._v_isopen:
return # the node is already closed
# .. note::
#
# As long as ``Table`` objects access their indices on closing,
# ``File.close()`` will need to make *two separate passes*
# to first close ``Table`` objects and then ``Index`` hierarchies.
#
# Flush right now so the row object does not get in the middle.
if flush:
self.flush()
# Some warnings can be issued after calling `self._g_set_location()`
# in `self.__init__()`. If warnings are turned into exceptions,
# `self._g_post_init_hook` may not be called and `self.cols` not set.
# One example of this is
# ``test_create.createTestCase.test05_maxFieldsExceeded()``.
cols = self.cols
if cols is not None:
cols._g_close()
# Clean address cache
self._clean_chunk_addrs()
# Close myself as a leaf.
super()._f_close(False)
def __repr__(self):
"""This provides column metainfo in addition to standard __str__"""
if self.indexed:
format = """\
%s
description := %r
byteorder := %r
chunkshape := %r
autoindex := %r
colindexes := %r"""
return format % (str(self), self.description, self.byteorder,
self.chunkshape, self.autoindex,
_ColIndexes(self.colindexes))
else:
return """\
%s
description := %r
byteorder := %r
chunkshape := %r""" % \
(str(self), self.description, self.byteorder, self.chunkshape)
| (parentnode, name, description=None, title='', filters=None, expectedrows=None, chunkshape=None, byteorder=None, _log=True, track_times=True) |
728,831 | tables.table | __getitem__ | Get a row or a range of rows from the table.
If key argument is an integer, the corresponding table row is returned
as a record of the current flavor. If key is a slice, the range of rows
determined by it is returned as a structured array of the current
flavor.
In addition, NumPy-style point selections are supported. In
particular, if key is a list of row coordinates, the set of rows
determined by it is returned. Furthermore, if key is an array of
boolean values, only the coordinates where key is True are returned.
Note that for the latter to work it is necessary that key list would
contain exactly as many rows as the table has.
Examples
--------
::
record = table[4]
recarray = table[4:1000:2]
recarray = table[[4,1000]] # only retrieves rows 4 and 1000
recarray = table[[True, False, ..., True]]
Those statements are equivalent to::
record = table.read(start=4)[0]
recarray = table.read(start=4, stop=1000, step=2)
recarray = table.read_coordinates([4,1000])
recarray = table.read_coordinates([True, False, ..., True])
Here, you can see how indexing can be used as a shorthand for the
:meth:`Table.read` and :meth:`Table.read_coordinates` methods.
| def __getitem__(self, key):
"""Get a row or a range of rows from the table.
If key argument is an integer, the corresponding table row is returned
as a record of the current flavor. If key is a slice, the range of rows
determined by it is returned as a structured array of the current
flavor.
In addition, NumPy-style point selections are supported. In
particular, if key is a list of row coordinates, the set of rows
determined by it is returned. Furthermore, if key is an array of
boolean values, only the coordinates where key is True are returned.
Note that for the latter to work it is necessary that key list would
contain exactly as many rows as the table has.
Examples
--------
::
record = table[4]
recarray = table[4:1000:2]
recarray = table[[4,1000]] # only retrieves rows 4 and 1000
recarray = table[[True, False, ..., True]]
Those statements are equivalent to::
record = table.read(start=4)[0]
recarray = table.read(start=4, stop=1000, step=2)
recarray = table.read_coordinates([4,1000])
recarray = table.read_coordinates([True, False, ..., True])
Here, you can see how indexing can be used as a shorthand for the
:meth:`Table.read` and :meth:`Table.read_coordinates` methods.
"""
self._g_check_open()
if is_idx(key):
key = operator.index(key)
# Index out of range protection
if key >= self.nrows:
raise IndexError("Index out of range")
if key < 0:
# To support negative values
key += self.nrows
(start, stop, step) = self._process_range(key, key + 1, 1)
return self.read(start, stop, step)[0]
elif isinstance(key, slice):
(start, stop, step) = self._process_range(
key.start, key.stop, key.step)
return self.read(start, stop, step)
# Try with a boolean or point selection
elif type(key) in (list, tuple) or isinstance(key, np.ndarray):
return self._read_coordinates(key, None)
else:
raise IndexError(f"Invalid index or slice: {key!r}")
| (self, key) |
728,832 | tables.table | __init__ | null | def __init__(self, parentnode, name,
description=None, title="", filters=None,
expectedrows=None, chunkshape=None,
byteorder=None, _log=True, track_times=True):
self._v_new = new = description is not None
"""Is this the first time the node has been created?"""
self._v_new_title = title
"""New title for this node."""
self._v_new_filters = filters
"""New filter properties for this node."""
self.extdim = 0 # Tables only have one dimension currently
"""The index of the enlargeable dimension (always 0 for tables)."""
self._v_recarray = None
"""A structured array to be stored in the table."""
self._rabyteorder = None
"""The computed byteorder of the self._v_recarray."""
if expectedrows is None:
expectedrows = parentnode._v_file.params['EXPECTED_ROWS_TABLE']
self._v_expectedrows = expectedrows
"""The expected number of rows to be stored in the table."""
self.nrows = SizeType(0)
"""The current number of rows in the table."""
self.description = None
"""A Description instance (see :ref:`DescriptionClassDescr`)
reflecting the structure of the table."""
self._time64colnames = []
"""The names of ``Time64`` columns."""
self._strcolnames = []
"""The names of ``String`` columns."""
self._colenums = {}
"""Maps the name of an enumerated column to its ``Enum`` instance."""
self._v_chunkshape = None
"""Private storage for the `chunkshape` property of the leaf."""
self.indexed = False
"""Does this table have any indexed columns?"""
self._indexedrows = 0
"""Number of rows indexed in disk."""
self._unsaved_indexedrows = 0
"""Number of rows indexed in memory but still not in disk."""
self._listoldindexes = []
"""The list of columns with old indexes."""
self._autoindex = None
"""Private variable that caches the value for autoindex."""
self.colnames = []
"""A list containing the names of *top-level* columns in the table."""
self.colpathnames = []
"""A list containing the pathnames of *bottom-level* columns in the
table.
These are the leaf columns obtained when walking the
table description left-to-right, bottom-first. Columns inside a
nested column have slashes (/) separating name components in
their pathname.
"""
self.colinstances = {}
"""Maps the name of a column to its Column (see
:ref:`ColumnClassDescr`) or Cols (see :ref:`ColsClassDescr`)
instance."""
self.coldescrs = {}
"""Maps the name of a column to its Col description (see
:ref:`ColClassDescr`)."""
self.coltypes = {}
"""Maps the name of a column to its PyTables data type."""
self.coldtypes = {}
"""Maps the name of a column to its NumPy data type."""
self.coldflts = {}
"""Maps the name of a column to its default value."""
self.colindexed = {}
"""Is the column which name is used as a key indexed?"""
self._use_index = False
"""Whether an index can be used or not in a search. Boolean."""
self._where_condition = None
"""Condition function and argument list for selection of values."""
self._seqcache_key = None
"""The key under which to save a query's results (list of row indexes)
or None to not save."""
max_slots = parentnode._v_file.params['COND_CACHE_SLOTS']
self._condition_cache = CacheDict(max_slots)
"""Cache of already compiled conditions."""
self._exprvars_cache = {}
"""Cache of variables participating in numexpr expressions."""
self._enabled_indexing_in_queries = True
"""Is indexing enabled in queries? *Use only for testing.*"""
self._empty_array_cache = {}
"""Cache of empty arrays."""
self._v_dtype = None
"""The NumPy datatype fopr this table."""
self.cols = None
"""
A Cols instance that provides *natural naming* access to non-nested
(Column, see :ref:`ColumnClassDescr`) and nested (Cols, see
:ref:`ColsClassDescr`) columns.
"""
self._dirtycache = True
"""Whether the data caches are dirty or not. Initially set to yes."""
self._descflavor = None
"""Temporarily keeps the flavor of a description with data."""
# Initialize this object in case is a new Table
# Try purely descriptive description objects.
if new and isinstance(description, dict):
# Dictionary case
self.description = Description(description,
ptparams=parentnode._v_file.params)
elif new and (type(description) == type(IsDescription)
and issubclass(description, IsDescription)):
# IsDescription subclass case
descr = description()
self.description = Description(descr.columns,
ptparams=parentnode._v_file.params)
elif new and isinstance(description, Description):
# It is a Description instance already
self.description = description
# No description yet?
if new and self.description is None:
# Try NumPy dtype instances
if isinstance(description, np.dtype):
tup = descr_from_dtype(description,
ptparams=parentnode._v_file.params)
self.description, self._rabyteorder = tup
# No description yet?
if new and self.description is None:
# Try structured array description objects.
try:
self._descflavor = flavor = flavor_of(description)
except TypeError: # probably not an array
pass
else:
if flavor == 'python':
nparray = np.rec.array(description)
else:
nparray = array_as_internal(description, flavor)
self.nrows = nrows = SizeType(nparray.size)
# If `self._v_recarray` is set, it will be used as the
# initial buffer.
if nrows > 0:
self._v_recarray = nparray
tup = descr_from_dtype(nparray.dtype,
ptparams=parentnode._v_file.params)
self.description, self._rabyteorder = tup
# No description yet?
if new and self.description is None:
raise TypeError(
"the ``description`` argument is not of a supported type: "
"``IsDescription`` subclass, ``Description`` instance, "
"dictionary, or structured array")
# Check the chunkshape parameter
if new and chunkshape is not None:
if isinstance(chunkshape, (int, np.integer)):
chunkshape = (chunkshape,)
try:
chunkshape = tuple(chunkshape)
except TypeError:
raise TypeError(
"`chunkshape` parameter must be an integer or sequence "
"and you passed a %s" % type(chunkshape))
if len(chunkshape) != 1:
raise ValueError("`chunkshape` rank (length) must be 1: %r"
% (chunkshape,))
self._v_chunkshape = tuple(SizeType(s) for s in chunkshape)
super().__init__(parentnode, name, new, filters, byteorder, _log,
track_times)
| (self, parentnode, name, description=None, title='', filters=None, expectedrows=None, chunkshape=None, byteorder=None, _log=True, track_times=True) |
728,833 | tables.table | __iter__ | Iterate over the table using a Row instance.
This is equivalent to calling :meth:`Table.iterrows` with default
arguments, i.e. it iterates over *all the rows* in the table.
See Also
--------
tableextension.Row : the table row iterator and field accessor
Examples
--------
::
result = [ row['var2'] for row in table if row['var1'] <= 20 ]
Which is equivalent to::
result = [ row['var2'] for row in table.iterrows()
if row['var1'] <= 20 ]
| def __iter__(self):
"""Iterate over the table using a Row instance.
This is equivalent to calling :meth:`Table.iterrows` with default
arguments, i.e. it iterates over *all the rows* in the table.
See Also
--------
tableextension.Row : the table row iterator and field accessor
Examples
--------
::
result = [ row['var2'] for row in table if row['var1'] <= 20 ]
Which is equivalent to::
result = [ row['var2'] for row in table.iterrows()
if row['var1'] <= 20 ]
"""
return self.iterrows()
| (self) |
728,835 | tables.table | __repr__ | This provides column metainfo in addition to standard __str__ | """Here is defined the Table class."""
import functools
import math
import operator
import sys
import warnings
from pathlib import Path
import weakref
from time import perf_counter as clock
import numexpr as ne
import numpy as np
from . import tableextension
from .lrucacheextension import ObjectCache, NumCache
from .atom import Atom
from .conditions import compile_condition
from .flavor import flavor_of, array_as_internal, internal_to_flavor
from .utils import is_idx, lazyattr, SizeType, NailedDict as CacheDict
from .leaf import Leaf
from .description import (IsDescription, Description, Col, descr_from_dtype)
from .exceptions import (
NodeError, HDF5ExtError, PerformanceWarning, OldIndexWarning,
NoSuchNodeError)
from .utilsextension import get_nested_field
from .path import join_path, split_path
from .index import (
OldIndex, default_index_filters, default_auto_index, Index, IndexesDescG,
IndexesTableG)
profile = False
# profile = True # Uncomment for profiling
if profile:
from .utils import show_stats
# 2.2: Added support for complex types. Introduced in version 0.9.
# 2.2.1: Added support for time types.
# 2.3: Changed the indexes naming schema.
# 2.4: Changed indexes naming schema (again).
# 2.5: Added the FIELD_%d_FILL attributes.
# 2.6: Added the FLAVOR attribute (optional).
# 2.7: Numeric and numarray flavors are gone.
obversion = "2.7" # The Table VERSION number
# Maps NumPy types to the types used by Numexpr.
_nxtype_from_nptype = {
np.bool_: bool,
np.int8: ne.necompiler.int_,
np.int16: ne.necompiler.int_,
np.int32: ne.necompiler.int_,
np.int64: ne.necompiler.long_,
np.uint8: ne.necompiler.int_,
np.uint16: ne.necompiler.int_,
np.uint32: ne.necompiler.long_,
np.uint64: ne.necompiler.long_,
np.float32: float,
np.float64: ne.necompiler.double,
np.complex64: complex,
np.complex128: complex,
np.bytes_: bytes,
}
_nxtype_from_nptype[np.str_] = str
if hasattr(np, 'float16'):
_nxtype_from_nptype[np.float16] = float # XXX: check
if hasattr(np, 'float96'):
_nxtype_from_nptype[np.float96] = ne.necompiler.double # XXX: check
if hasattr(np, 'float128'):
_nxtype_from_nptype[np.float128] = ne.necompiler.double # XXX: check
if hasattr(np, 'complex192'):
_nxtype_from_nptype[np.complex192] = complex # XXX: check
if hasattr(np, 'complex256'):
_nxtype_from_nptype[np.complex256] = complex # XXX: check
# The NumPy scalar type corresponding to `SizeType`.
_npsizetype = np.array(SizeType(0)).dtype.type
def _index_name_of(node):
return '_i_%s' % node._v_name
| (self) |
728,836 | tables.table | __setitem__ | Set a row or a range of rows in the table.
It takes different actions depending on the type of the *key*
parameter: if it is an integer, the corresponding table row is
set to *value* (a record or sequence capable of being converted
to the table structure). If *key* is a slice, the row slice
determined by it is set to *value* (a record array or sequence
capable of being converted to the table structure).
In addition, NumPy-style point selections are supported. In
particular, if key is a list of row coordinates, the set of rows
determined by it is set to value. Furthermore, if key is an array of
boolean values, only the coordinates where key is True are set to
values from value. Note that for the latter to work it is necessary
that key list would contain exactly as many rows as the table has.
Examples
--------
::
# Modify just one existing row
table[2] = [456,'db2',1.2]
# Modify two existing rows
rows = np.rec.array(
[[457,'db1',1.2],[6,'de2',1.3]], formats='i4,S3,f8'
)
table[1:30:2] = rows # modify a table slice
table[[1,3]] = rows # only modifies rows 1 and 3
table[[True,False,True]] = rows # only modifies rows 0 and 2
Which is equivalent to::
table.modify_rows(start=2, rows=[456,'db2',1.2])
rows = np.rec.array(
[[457,'db1',1.2],[6,'de2',1.3]], formats='i4,S3,f8'
)
table.modify_rows(start=1, stop=3, step=2, rows=rows)
table.modify_coordinates([1,3,2], rows)
table.modify_coordinates([True, False, True], rows)
Here, you can see how indexing can be used as a shorthand for the
:meth:`Table.modify_rows` and :meth:`Table.modify_coordinates`
methods.
| def __setitem__(self, key, value):
"""Set a row or a range of rows in the table.
It takes different actions depending on the type of the *key*
parameter: if it is an integer, the corresponding table row is
set to *value* (a record or sequence capable of being converted
to the table structure). If *key* is a slice, the row slice
determined by it is set to *value* (a record array or sequence
capable of being converted to the table structure).
In addition, NumPy-style point selections are supported. In
particular, if key is a list of row coordinates, the set of rows
determined by it is set to value. Furthermore, if key is an array of
boolean values, only the coordinates where key is True are set to
values from value. Note that for the latter to work it is necessary
that key list would contain exactly as many rows as the table has.
Examples
--------
::
# Modify just one existing row
table[2] = [456,'db2',1.2]
# Modify two existing rows
rows = np.rec.array(
[[457,'db1',1.2],[6,'de2',1.3]], formats='i4,S3,f8'
)
table[1:30:2] = rows # modify a table slice
table[[1,3]] = rows # only modifies rows 1 and 3
table[[True,False,True]] = rows # only modifies rows 0 and 2
Which is equivalent to::
table.modify_rows(start=2, rows=[456,'db2',1.2])
rows = np.rec.array(
[[457,'db1',1.2],[6,'de2',1.3]], formats='i4,S3,f8'
)
table.modify_rows(start=1, stop=3, step=2, rows=rows)
table.modify_coordinates([1,3,2], rows)
table.modify_coordinates([True, False, True], rows)
Here, you can see how indexing can be used as a shorthand for the
:meth:`Table.modify_rows` and :meth:`Table.modify_coordinates`
methods.
"""
self._g_check_open()
self._v_file._check_writable()
if is_idx(key):
key = operator.index(key)
# Index out of range protection
if key >= self.nrows:
raise IndexError("Index out of range")
if key < 0:
# To support negative values
key += self.nrows
return self.modify_rows(key, key + 1, 1, [value])
elif isinstance(key, slice):
(start, stop, step) = self._process_range(
key.start, key.stop, key.step)
return self.modify_rows(start, stop, step, value)
# Try with a boolean or point selection
elif type(key) in (list, tuple) or isinstance(key, np.ndarray):
return self.modify_coordinates(key, value)
else:
raise IndexError(f"Invalid index or slice: {key!r}")
| (self, key, value) |
728,838 | tables.table | _add_rows_to_index | Add more elements to the existing index. | def _add_rows_to_index(self, colname, start, nrows, lastrow, update):
"""Add more elements to the existing index."""
# This method really belongs to Column, but since it makes extensive
# use of the table, it gets dangerous when closing the file, since the
# column may be accessing a table which is being destroyed.
index = self.cols._g_col(colname).index
slicesize = index.slicesize
# The next loop does not rely on xrange so that it can
# deal with long ints (i.e. more than 32-bit integers)
# This allows to index columns with more than 2**31 rows
# F. Alted 2005-05-09
startLR = index.sorted.nrows * slicesize
indexedrows = startLR - start
stop = start + nrows - slicesize + 1
while startLR < stop:
index.append(
[self._read(startLR, startLR + slicesize, 1, colname)],
update=update)
indexedrows += slicesize
startLR += slicesize
# index the remaining rows in last row
if lastrow and startLR < self.nrows:
index.append_last_row(
[self._read(startLR, self.nrows, 1, colname)],
update=update)
indexedrows += self.nrows - startLR
return indexedrows
| (self, colname, start, nrows, lastrow, update) |
728,839 | tables.table | _cache_description_data | Cache some data which is already in the description.
Some information is extracted from `self.description` to build
some useful (but redundant) structures:
* `self.colnames`
* `self.colpathnames`
* `self.coldescrs`
* `self.coltypes`
* `self.coldtypes`
* `self.coldflts`
* `self._v_dtype`
* `self._time64colnames`
* `self._strcolnames`
* `self._colenums`
| def _cache_description_data(self):
"""Cache some data which is already in the description.
Some information is extracted from `self.description` to build
some useful (but redundant) structures:
* `self.colnames`
* `self.colpathnames`
* `self.coldescrs`
* `self.coltypes`
* `self.coldtypes`
* `self.coldflts`
* `self._v_dtype`
* `self._time64colnames`
* `self._strcolnames`
* `self._colenums`
"""
self.colnames = list(self.description._v_names)
self.colpathnames = [
col._v_pathname for col in self.description._f_walk()
if not hasattr(col, '_v_names')] # bottom-level
# Find ``time64`` column names.
self._time64colnames = self._get_type_col_names('time64')
# Find ``string`` column names.
self._strcolnames = self._get_type_col_names('string')
# Get a mapping of enumerated columns to their `Enum` instances.
self._colenums = self._get_enum_map()
# Get info about columns
for colobj in self.description._f_walk(type="Col"):
colname = colobj._v_pathname
# Get the column types, types and defaults
self.coldescrs[colname] = colobj
self.coltypes[colname] = colobj.type
self.coldtypes[colname] = colobj.dtype
self.coldflts[colname] = colobj.dflt
# Assign _v_dtype for this table
self._v_dtype = self.description._v_dtype
| (self) |
728,841 | tables.table | _calc_nrowsinbuf | Calculate the number of rows that fits on a PyTables buffer. | def _calc_nrowsinbuf(self):
"""Calculate the number of rows that fits on a PyTables buffer."""
params = self._v_file.params
# Compute the nrowsinbuf
rowsize = self.rowsize
buffersize = params['IO_BUFFER_SIZE']
if rowsize != 0:
nrowsinbuf = buffersize // rowsize
# The number of rows in buffer needs to be an exact multiple of
# chunkshape[0] for queries using indexed columns.
# Fixes #319 and probably #409 too.
nrowsinbuf -= nrowsinbuf % self.chunkshape[0]
else:
nrowsinbuf = 1
# tableextension.pyx performs an assertion
# to make sure nrowsinbuf is greater than or
# equal to the chunksize.
# See gh-206 and gh-238
if self.chunkshape is not None:
if nrowsinbuf < self.chunkshape[0]:
nrowsinbuf = self.chunkshape[0]
# Safeguard against row sizes being extremely large
if nrowsinbuf == 0:
nrowsinbuf = 1
# If rowsize is too large, issue a Performance warning
maxrowsize = params['BUFFER_TIMES'] * buffersize
if rowsize > maxrowsize:
warnings.warn("""\
The Table ``%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 *main*
dimension of this leave. Alternatively, in case you have specified a
very small/large chunksize, you may want to increase/decrease it."""
% (self._v_pathname, maxrowsize),
PerformanceWarning)
return nrowsinbuf
| (self) |
728,842 | tables.table | _get_column_instance | Get the instance of the column with the given `colpathname`.
If the column does not exist in the table, a `KeyError` is
raised.
| def _get_column_instance(self, colpathname):
"""Get the instance of the column with the given `colpathname`.
If the column does not exist in the table, a `KeyError` is
raised.
"""
try:
return functools.reduce(
getattr, colpathname.split('/'), self.description)
except AttributeError:
raise KeyError("table ``%s`` does not have a column named ``%s``"
% (self._v_pathname, colpathname))
| (self, colpathname) |
728,843 | tables.table | _check_sortby_csi | null | def _check_sortby_csi(self, sortby, checkCSI):
if isinstance(sortby, Column):
icol = sortby
elif isinstance(sortby, str):
icol = self.cols._f_col(sortby)
else:
raise TypeError(
"`sortby` can only be a `Column` or string object, "
"but you passed an object of type: %s" % type(sortby))
if icol.is_indexed and icol.index.kind == "full":
if checkCSI and not icol.index.is_csi:
# The index exists, but it is not a CSI one.
raise ValueError(
"Field `%s` must have associated a CSI index "
"in table `%s`, but the existing one is not. "
% (sortby, self))
return icol.index
else:
raise ValueError(
"Field `%s` must have associated a 'full' index "
"in table `%s`." % (sortby, self))
| (self, sortby, checkCSI) |
728,844 | tables.table | _compile_condition | Compile the `condition` and extract usable index conditions.
This method returns an instance of ``CompiledCondition``. See
the ``compile_condition()`` function in the ``conditions``
module for more information about the compilation process.
This method makes use of the condition cache when possible.
| def _compile_condition(self, condition, condvars):
"""Compile the `condition` and extract usable index conditions.
This method returns an instance of ``CompiledCondition``. See
the ``compile_condition()`` function in the ``conditions``
module for more information about the compilation process.
This method makes use of the condition cache when possible.
"""
# Look up the condition in the condition cache.
condcache = self._condition_cache
condkey = self._get_condition_key(condition, condvars)
compiled = condcache.get(condkey)
if compiled:
return compiled.with_replaced_vars(condvars) # bingo!
# Bad luck, the condition must be parsed and compiled.
# Fortunately, the key provides some valuable information. ;)
(condition, colnames, varnames, colpaths, vartypes) = condkey
# Extract more information from referenced columns.
# start with normal variables
typemap = dict(list(zip(varnames, vartypes)))
indexedcols = []
for colname in colnames:
col = condvars[colname]
# Extract types from *all* the given variables.
coltype = col.dtype.type
typemap[colname] = _nxtype_from_nptype[coltype]
# Get the set of columns with usable indexes.
if (self._enabled_indexing_in_queries # no in-kernel searches
and self.colindexed[col.pathname] and not col.index.dirty):
indexedcols.append(colname)
indexedcols = frozenset(indexedcols)
# Now let ``compile_condition()`` do the Numexpr-related job.
compiled = compile_condition(condition, typemap, indexedcols)
# Check that there actually are columns in the condition.
if not set(compiled.parameters).intersection(set(colnames)):
raise ValueError("there are no columns taking part "
"in condition ``%s``" % (condition,))
# Store the compiled condition in the cache and return it.
condcache[condkey] = compiled
return compiled.with_replaced_vars(condvars)
| (self, condition, condvars) |
728,845 | tables.table | _conv_to_recarr | Try to convert the object into a recarray. | def _conv_to_recarr(self, obj):
"""Try to convert the object into a recarray."""
try:
iflavor = flavor_of(obj)
if iflavor != 'python':
obj = array_as_internal(obj, iflavor)
if hasattr(obj, "shape") and obj.shape == ():
# To allow conversion of scalars (void type) into arrays.
# See http://projects.scipy.org/scipy/numpy/ticket/315
# for discussion on how to pass buffers to constructors
# See also http://projects.scipy.org/scipy/numpy/ticket/348
recarr = np.array([obj], dtype=self._v_dtype)
else:
# Works for Python structures and always copies the original,
# so the resulting object is safe for in-place conversion.
recarr = np.rec.array(obj, dtype=self._v_dtype)
except Exception as exc: # XXX
raise ValueError("Object cannot be converted into a recarray "
"object compliant with table format '%s'. "
"The error was: <%s>" %
(self.description._v_nested_descr, exc))
return recarr
| (self, obj) |
728,846 | tables.table | _disable_indexing_in_queries | Force queries not to use indexing.
*Use only for testing.*
| def _disable_indexing_in_queries(self):
"""Force queries not to use indexing.
*Use only for testing.*
"""
if not self._enabled_indexing_in_queries:
return # already disabled
# The nail avoids setting/getting compiled conditions in/from
# the cache where indexing is used.
self._condition_cache.nail()
self._enabled_indexing_in_queries = False
| (self) |
728,847 | tables.table | _do_reindex | Common code for `reindex()` and `reindex_dirty()`. | def _do_reindex(self, dirty):
"""Common code for `reindex()` and `reindex_dirty()`."""
indexedrows = 0
for (colname, colindexed) in self.colindexed.items():
if colindexed:
indexcol = self.cols._g_col(colname)
indexedrows = indexcol._do_reindex(dirty)
# Update counters in case some column has been updated
if indexedrows > 0:
self._indexedrows = indexedrows
self._unsaved_indexedrows = self.nrows - indexedrows
return SizeType(indexedrows)
| (self, dirty) |
728,848 | tables.table | _enable_indexing_in_queries | Allow queries to use indexing.
*Use only for testing.*
| def _enable_indexing_in_queries(self):
"""Allow queries to use indexing.
*Use only for testing.*
"""
if self._enabled_indexing_in_queries:
return # already enabled
self._condition_cache.unnail()
self._enabled_indexing_in_queries = True
| (self) |
728,849 | tables.table | _f_close | null | def _f_close(self, flush=True):
if not self._v_isopen:
return # the node is already closed
# .. note::
#
# As long as ``Table`` objects access their indices on closing,
# ``File.close()`` will need to make *two separate passes*
# to first close ``Table`` objects and then ``Index`` hierarchies.
#
# Flush right now so the row object does not get in the middle.
if flush:
self.flush()
# Some warnings can be issued after calling `self._g_set_location()`
# in `self.__init__()`. If warnings are turned into exceptions,
# `self._g_post_init_hook` may not be called and `self.cols` not set.
# One example of this is
# ``test_create.createTestCase.test05_maxFieldsExceeded()``.
cols = self.cols
if cols is not None:
cols._g_close()
# Clean address cache
self._clean_chunk_addrs()
# Close myself as a leaf.
super()._f_close(False)
| (self, flush=True) |
728,864 | tables.table | _g_copy_rows | Copy rows from self to object | def _g_copy_rows(self, object, start, stop, step, sortby, checkCSI):
"""Copy rows from self to object"""
if sortby is None:
self._g_copy_rows_optim(object, start, stop, step)
return
lenbuf = self.nrowsinbuf
absstep = step
if step < 0:
absstep = -step
start, stop = stop + 1, start + 1
if sortby is not None:
index = self._check_sortby_csi(sortby, checkCSI)
for start2 in range(start, stop, absstep * lenbuf):
stop2 = start2 + absstep * lenbuf
if stop2 > stop:
stop2 = stop
# The next 'if' is not needed, but it doesn't bother either
if sortby is None:
rows = self[start2:stop2:step]
else:
coords = index[start2:stop2:step]
rows = self.read_coordinates(coords)
# Save the records on disk
object.append(rows)
object.flush()
| (self, object, start, stop, step, sortby, checkCSI) |
728,865 | tables.table | _g_copy_rows_optim | Copy rows from self to object (optimized version) | def _g_copy_rows_optim(self, object, start, stop, step):
"""Copy rows from self to object (optimized version)"""
nrowsinbuf = self.nrowsinbuf
object._open_append(self._v_iobuf)
nrowsdest = object.nrows
for start2 in range(start, stop, step * nrowsinbuf):
# Save the records on disk
stop2 = start2 + step * nrowsinbuf
if stop2 > stop:
stop2 = stop
# Optimized version (it saves some conversions)
nrows = ((stop2 - start2 - 1) // step) + 1
self.row._fill_col(self._v_iobuf, start2, stop2, step, None)
# The output buffer is created anew,
# so the operation is safe to in-place conversion.
object._append_records(nrows)
nrowsdest += nrows
object._close_append()
| (self, object, start, stop, step) |
728,866 | tables.table | _g_copy_with_stats | Private part of Leaf.copy() for each kind of leaf. | def _g_copy_with_stats(self, group, name, start, stop, step,
title, filters, chunkshape, _log, **kwargs):
"""Private part of Leaf.copy() for each kind of leaf."""
# Get the private args for the Table flavor of copy()
sortby = kwargs.pop('sortby', None)
propindexes = kwargs.pop('propindexes', False)
checkCSI = kwargs.pop('checkCSI', False)
# Compute the correct indices.
(start, stop, step) = self._process_range_read(
start, stop, step, warn_negstep=sortby is None)
# And the number of final rows
nrows = len(range(start, stop, step))
# Create the new table and copy the selected data.
newtable = Table(group, name, self.description, title=title,
filters=filters, expectedrows=nrows,
chunkshape=chunkshape,
_log=_log)
self._g_copy_rows(newtable, start, stop, step, sortby, checkCSI)
nbytes = newtable.nrows * newtable.rowsize
# Generate equivalent indexes in the new table, if required.
if propindexes and self.indexed:
self._g_prop_indexes(newtable)
return (newtable, nbytes)
| (self, group, name, start, stop, step, title, filters, chunkshape, _log, **kwargs) |
728,867 | tables.table | _g_create | Create a new table on disk. | def _g_create(self):
"""Create a new table on disk."""
# Warning against assigning too much columns...
# F. Alted 2005-06-05
maxColumns = self._v_file.params['MAX_COLUMNS']
if (len(self.description._v_names) > maxColumns):
warnings.warn(
"table ``%s`` is exceeding the recommended "
"maximum number of columns (%d); "
"be ready to see PyTables asking for *lots* of memory "
"and possibly slow I/O" % (self._v_pathname, maxColumns),
PerformanceWarning)
# 1. Create the HDF5 table (some parameters need to be computed).
# Fix the byteorder of the recarray and update the number of
# expected rows if necessary
if self._v_recarray is not None:
self._v_recarray = self._g_fix_byteorder_data(self._v_recarray,
self._rabyteorder)
if len(self._v_recarray) > self._v_expectedrows:
self._v_expectedrows = len(self._v_recarray)
# Compute a sensible chunkshape
if self._v_chunkshape is None:
self._v_chunkshape = self._calc_chunkshape(
self._v_expectedrows, self.rowsize, self.rowsize)
# Correct the byteorder, if still needed
if self.byteorder is None:
self.byteorder = sys.byteorder
# Cache some data which is already in the description.
# This is necessary to happen before creation time in order
# to be able to populate the self._v_wdflts
self._cache_description_data()
# After creating the table, ``self._v_objectid`` needs to be
# set because it is needed for setting attributes afterwards.
self._v_objectid = self._create_table(
self._v_new_title, self.filters.complib or '', obversion)
self._v_recarray = None # not useful anymore
self._rabyteorder = None # not useful anymore
# 2. Compute or get chunk shape and buffer size parameters.
self.nrowsinbuf = self._calc_nrowsinbuf()
# 3. Get field fill attributes from the table description and
# set them on disk.
if self._v_file.params['PYTABLES_SYS_ATTRS']:
set_attr = self._v_attrs._g__setattr
for i, colobj in enumerate(self.description._f_walk(type="Col")):
fieldname = "FIELD_%d_FILL" % i
set_attr(fieldname, colobj.dflt)
return self._v_objectid
| (self) |
728,875 | tables.table | _g_move | Move this node in the hierarchy.
This overloads the Node._g_move() method.
| def _g_move(self, newparent, newname):
"""Move this node in the hierarchy.
This overloads the Node._g_move() method.
"""
itgpathname = _index_pathname_of(self)
# First, move the table to the new location.
super()._g_move(newparent, newname)
# Then move the associated index group (if any).
try:
itgroup = self._v_file._get_node(itgpathname)
except NoSuchNodeError:
pass
else:
newigroup = self._v_parent
newiname = _index_name_of(self)
itgroup._g_move(newigroup, newiname)
| (self, newparent, newname) |
728,876 | tables.table | _g_open | Opens a table from disk and read the metadata on it.
Creates an user description on the flight to easy the access to
the actual data.
| def _g_open(self):
"""Opens a table from disk and read the metadata on it.
Creates an user description on the flight to easy the access to
the actual data.
"""
# 1. Open the HDF5 table and get some data from it.
self._v_objectid, description, chunksize = self._get_info()
self._v_expectedrows = self.nrows # the actual number of rows
# 2. Create an instance description to host the record fields.
validate = not self._v_file._isPTFile # only for non-PyTables files
self.description = Description(description, validate=validate,
ptparams=self._v_file.params)
# 3. Compute or get chunk shape and buffer size parameters.
if chunksize == 0:
self._v_chunkshape = self._calc_chunkshape(
self._v_expectedrows, self.rowsize, self.rowsize)
else:
self._v_chunkshape = (chunksize,)
self.nrowsinbuf = self._calc_nrowsinbuf()
# 4. If there are field fill attributes, get them from disk and
# set them in the table description.
if self._v_file.params['PYTABLES_SYS_ATTRS']:
if "FIELD_0_FILL" in self._v_attrs._f_list("sys"):
i = 0
get_attr = self._v_attrs.__getattr__
for objcol in self.description._f_walk(type="Col"):
colname = objcol._v_pathname
# Get the default values for each column
fieldname = "FIELD_%s_FILL" % i
defval = get_attr(fieldname)
if defval is not None:
objcol.dflt = defval
else:
warnings.warn("could not load default value "
"for the ``%s`` column of table ``%s``; "
"using ``%r`` instead"
% (colname, self._v_pathname,
objcol.dflt))
defval = objcol.dflt
i += 1
# Set also the correct value in the desc._v_dflts dictionary
for descr in self.description._f_walk(type="Description"):
for name in descr._v_names:
objcol = descr._v_colobjects[name]
if isinstance(objcol, Col):
descr._v_dflts[objcol._v_name] = objcol.dflt
# 5. Cache some data which is already in the description.
self._cache_description_data()
return self._v_objectid
| (self) |
728,877 | tables.table | _g_post_init_hook | null | def _g_post_init_hook(self):
# We are putting here the index-related issues
# as well as filling general info for table
# This is needed because we need first the index objects created
# First, get back the flavor of input data (if any) for
# `Leaf._g_post_init_hook()`.
self._flavor, self._descflavor = self._descflavor, None
super()._g_post_init_hook()
# Create a cols accessor.
self.cols = Cols(self, self.description)
# Place the `Cols` and `Column` objects into `self.colinstances`.
colinstances, cols = self.colinstances, self.cols
for colpathname in self.description._v_pathnames:
colinstances[colpathname] = cols._g_col(colpathname)
if self._v_new:
# Columns are never indexed on creation.
self.colindexed = {cpn: False for cpn in self.colpathnames}
return
# The following code is only for opened tables.
# Do the indexes group exist?
indexesgrouppath = _index_pathname_of(self)
igroup = indexesgrouppath in self._v_file
oldindexes = False
for colobj in self.description._f_walk(type="Col"):
colname = colobj._v_pathname
# Is this column indexed?
if igroup:
indexname = _index_pathname_of_column(self, colname)
indexed = indexname in self._v_file
self.colindexed[colname] = indexed
if indexed:
column = self.cols._g_col(colname)
indexobj = column.index
if isinstance(indexobj, OldIndex):
indexed = False # Not a vaild index
oldindexes = True
self._listoldindexes.append(colname)
else:
# Tell the condition cache about columns with dirty
# indexes.
if indexobj.dirty:
self._condition_cache.nail()
else:
indexed = False
self.colindexed[colname] = False
if indexed:
self.indexed = True
if oldindexes: # this should only appear under 2.x Pro
warnings.warn(
"table ``%s`` has column indexes with PyTables 1.x format. "
"Unfortunately, this format is not supported in "
"PyTables 2.x series. Note that you can use the "
"``ptrepack`` utility in order to recreate the indexes. "
"The 1.x indexed columns found are: %s" %
(self._v_pathname, self._listoldindexes),
OldIndexWarning)
# It does not matter to which column 'indexobj' belongs,
# since their respective index objects share
# the same number of elements.
if self.indexed:
self._indexedrows = indexobj.nelements
self._unsaved_indexedrows = self.nrows - self._indexedrows
# Put the autoindex value in a cache variable
self._autoindex = self.autoindex
| (self) |
728,878 | tables.table | _g_pre_kill_hook | Code to be called before killing the node. | def _g_pre_kill_hook(self):
"""Code to be called before killing the node."""
# Flush the buffers before to clean-up them
# self.flush()
# It seems that flushing during the __del__ phase is a sure receipt for
# bringing all kind of problems:
# 1. Illegal Instruction
# 2. Malloc(): trying to call free() twice
# 3. Bus Error
# 4. Segmentation fault
# So, the best would be doing *nothing* at all in this __del__ phase.
# As a consequence, the I/O will not be cleaned until a call to
# Table.flush() would be done. This could lead to a potentially large
# memory consumption.
# NOTE: The user should make a call to Table.flush() whenever he has
# finished working with his table.
# I've added a Performance warning in order to compel the user to
# call self.flush() before the table is being preempted.
# F. Alted 2006-08-03
if (('row' in self.__dict__ and self.row._get_unsaved_nrows() > 0) or
(self.indexed and self.autoindex and
(self._unsaved_indexedrows > 0 or self._dirtyindexes))):
warnings.warn(("table ``%s`` is being preempted from alive nodes "
"without its buffers being flushed or with some "
"index being dirty. This may lead to very "
"ineficient use of resources and even to fatal "
"errors in certain situations. Please do a call "
"to the .flush() or .reindex_dirty() methods on "
"this table before start using other nodes.")
% (self._v_pathname), PerformanceWarning)
# Get rid of the IO buffers (if they have been created at all)
mydict = self.__dict__
if '_v_iobuf' in mydict:
del mydict['_v_iobuf']
if '_v_wdflts' in mydict:
del mydict['_v_wdflts']
| (self) |
728,879 | tables.table | _g_prop_indexes | Generate index in `other` table for every indexed column here. | def _g_prop_indexes(self, other):
"""Generate index in `other` table for every indexed column here."""
oldcols, newcols = self.colinstances, other.colinstances
for colname in newcols:
if (isinstance(oldcols[colname], Column)):
oldcolindexed = oldcols[colname].is_indexed
if oldcolindexed:
oldcolindex = oldcols[colname].index
newcol = newcols[colname]
newcol.create_index(
kind=oldcolindex.kind, optlevel=oldcolindex.optlevel,
filters=oldcolindex.filters, tmp_dir=None)
| (self, other) |
728,880 | tables.table | _g_remove | null | def _g_remove(self, recursive=False, force=False):
# Remove the associated index group (if any).
itgpathname = _index_pathname_of(self)
try:
itgroup = self._v_file._get_node(itgpathname)
except NoSuchNodeError:
pass
else:
itgroup._f_remove(recursive=True)
self.indexed = False # there are indexes no more
# Remove the leaf itself from the hierarchy.
super()._g_remove(recursive, force)
| (self, recursive=False, force=False) |
728,884 | tables.table | _g_update_dependent | null | def _g_update_dependent(self):
super()._g_update_dependent()
# Update the new path in columns
self.cols._g_update_table_location(self)
# Update the new path in the Row instance, if cached. Fixes #224.
if 'row' in self.__dict__:
self.__dict__['row'] = tableextension.Row(self)
| (self) |
728,887 | tables.table | _get_condition_key | Get the condition cache key for `condition` with `condvars`.
Currently, the key is a tuple of `condition`, column variables
names, normal variables names, column paths and variable paths
(all are tuples).
| def _get_condition_key(self, condition, condvars):
"""Get the condition cache key for `condition` with `condvars`.
Currently, the key is a tuple of `condition`, column variables
names, normal variables names, column paths and variable paths
(all are tuples).
"""
# Variable names for column and normal variables.
colnames, varnames = [], []
# Column paths and types for each of the previous variable.
colpaths, vartypes = [], []
for (var, val) in condvars.items():
if hasattr(val, 'pathname'): # column
colnames.append(var)
colpaths.append(val.pathname)
else: # array
try:
varnames.append(var)
vartypes.append(ne.necompiler.getType(val)) # expensive
except ValueError:
# This is more clear than the error given by Numexpr.
raise TypeError("variable ``%s`` has data type ``%s``, "
"not allowed in conditions"
% (var, val.dtype.name))
colnames, varnames = tuple(colnames), tuple(varnames)
colpaths, vartypes = tuple(colpaths), tuple(vartypes)
condkey = (condition, colnames, varnames, colpaths, vartypes)
return condkey
| (self, condition, condvars) |
728,888 | tables.table | _get_container | Get the appropriate buffer for data depending on table
nestedness. | def _get_container(self, shape):
"""Get the appropriate buffer for data depending on table
nestedness."""
# This is *much* faster than the numpy.rec.array counterpart
return np.empty(shape=shape, dtype=self._v_dtype)
| (self, shape) |
728,889 | tables.table | _get_enum_map | Return mapping from enumerated column names to `Enum` instances. | def _get_enum_map(self):
"""Return mapping from enumerated column names to `Enum` instances."""
enumMap = {}
for colobj in self.description._f_walk('Col'):
if colobj.kind == 'enum':
enumMap[colobj._v_pathname] = colobj.enum
return enumMap
| (self) |
728,890 | tables.table | _get_type_col_names | Returns a list containing 'type_' column names. | def _get_type_col_names(self, type_):
"""Returns a list containing 'type_' column names."""
return [colobj._v_pathname
for colobj in self.description._f_walk('Col')
if colobj.type == type_]
| (self, type_) |
728,891 | tables.table | _getemptyarray | null | def _getemptyarray(self, dtype):
# Acts as a cache for empty arrays
key = dtype
if key in self._empty_array_cache:
return self._empty_array_cache[key]
else:
self._empty_array_cache[
key] = arr = np.empty(shape=0, dtype=key)
return arr
| (self, dtype) |
728,892 | tables.table | _mark_columns_as_dirty | Mark column indexes in `colnames` as dirty. | def _mark_columns_as_dirty(self, colnames):
"""Mark column indexes in `colnames` as dirty."""
assert len(colnames) > 0
if self.indexed:
colindexed, cols = self.colindexed, self.cols
# Mark the proper indexes as dirty
for colname in colnames:
if colindexed[colname]:
col = cols._g_col(colname)
col.index.dirty = True
| (self, colnames) |
728,896 | tables.table | _read | Read a range of rows and return an in-memory object. | def _read(self, start, stop, step, field=None, out=None):
"""Read a range of rows and return an in-memory object."""
select_field = None
if field:
if field not in self.coldtypes:
if field in self.description._v_names:
# Remember to select this field
select_field = field
field = None
else:
raise KeyError(("Field {} not found in table "
"{}").format(field, self))
else:
# The column hangs directly from the top
dtype_field = self.coldtypes[field]
# Return a rank-0 array if start > stop
if (start >= stop and 0 < step) or (start <= stop and 0 > step):
if field is None:
nra = self._get_container(0)
return nra
return np.empty(shape=0, dtype=dtype_field)
nrows = len(range(start, stop, step))
if out is None:
# Compute the shape of the resulting column object
if field:
# Create a container for the results
result = np.empty(shape=nrows, dtype=dtype_field)
else:
# Recarray case
result = self._get_container(nrows)
else:
# there is no fast way to byteswap, since different columns may
# have different byteorders
if not out.dtype.isnative:
raise ValueError("output array must be in system's byteorder "
"or results will be incorrect")
if field:
bytes_required = dtype_field.itemsize * nrows
else:
bytes_required = self.rowsize * nrows
if bytes_required != out.nbytes:
raise ValueError(f'output array size invalid, got {out.nbytes}'
f' bytes, need {bytes_required} bytes')
if not out.flags['C_CONTIGUOUS']:
raise ValueError('output array not C contiguous')
result = out
# Call the routine to fill-up the resulting array
if step == 1 and not field:
# This optimization works three times faster than
# the row._fill_col method (up to 170 MB/s on a pentium IV @ 2GHz)
self._read_records(start, stop - start, result)
# Warning!: _read_field_name should not be used until
# H5TBread_fields_name in tableextension will be finished
# F. Alted 2005/05/26
# XYX Ho implementem per a PyTables 2.0??
elif field and step > 15 and 0:
# For step>15, this seems to work always faster than row._fill_col.
self._read_field_name(result, start, stop, step, field)
else:
self.row._fill_col(result, start, stop, step, field)
if select_field:
return result[select_field]
else:
return result
| (self, start, stop, step, field=None, out=None) |
728,897 | tables.table | _read_coordinates | Private part of `read_coordinates()` with no flavor conversion. | def _read_coordinates(self, coords, field=None):
"""Private part of `read_coordinates()` with no flavor conversion."""
coords = self._point_selection(coords)
ncoords = len(coords)
# Create a read buffer only if needed
if field is None or ncoords > 0:
# Doing a copy is faster when ncoords is small (<1000)
if ncoords < min(1000, self.nrowsinbuf):
result = self._v_iobuf[:ncoords].copy()
else:
result = self._get_container(ncoords)
# Do the real read
if ncoords > 0:
# Turn coords into an array of coordinate indexes, if necessary
if not (isinstance(coords, np.ndarray) and
coords.dtype.type is _npsizetype and
coords.flags.contiguous and
coords.flags.aligned):
# Get a contiguous and aligned coordinate array
coords = np.array(coords, dtype=SizeType)
self._read_elements(coords, result)
# Do the final conversions, if needed
if field:
if ncoords > 0:
result = get_nested_field(result, field)
else:
# Get an empty array from the cache
result = self._getemptyarray(self.coldtypes[field])
return result
| (self, coords, field=None) |
728,898 | tables.table | _reindex | Re-index columns in `colnames` if automatic indexing is true. | def _reindex(self, colnames):
"""Re-index columns in `colnames` if automatic indexing is true."""
if self.indexed:
colindexed, cols = self.colindexed, self.cols
colstoindex = []
# Mark the proper indexes as dirty
for colname in colnames:
if colindexed[colname]:
col = cols._g_col(colname)
col.index.dirty = True
colstoindex.append(colname)
# Now, re-index the dirty ones
if self.autoindex and colstoindex:
self._do_reindex(dirty=True)
# The table caches for indexed queries are dirty now
self._dirtycache = True
| (self, colnames) |
728,899 | tables.table | _required_expr_vars | 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. This mechanism will not work as expected if this
method is not used *directly* from an API callable. To disable
this mechanism, just specify a mapping as `uservars`.
Nested columns and columns from other tables are not allowed
(`TypeError` and `ValueError` are raised, respectively). Also,
non-column variable values are converted to NumPy arrays.
`depth` specifies the depth of the frame in order to reach local
or global variables.
| def _required_expr_vars(self, expression, uservars, depth=1):
"""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. This mechanism will not work as expected if this
method is not used *directly* from an API callable. To disable
this mechanism, just specify a mapping as `uservars`.
Nested columns and columns from other tables are not allowed
(`TypeError` and `ValueError` are raised, respectively). Also,
non-column variable values are converted to NumPy arrays.
`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._exprvars_cache
if expression not in exprvarscache:
# Protection against growing the cache too much
if len(exprvarscache) > 256:
# Remove 10 (arbitrary) elements from the cache
for k in list(exprvarscache)[: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 ne.expressions.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:
# We use specified depth to get the frame where the API
# callable using this method is called. For instance:
#
# * ``table._required_expr_vars()`` (depth 0) is called by
# * ``table._where()`` (depth 1) is called by
# * ``table.where()`` (depth 2) is called by
# * user-space functions (depth 3)
user_frame = sys._getframe(depth)
user_locals = user_frame.f_locals
user_globals = user_frame.f_globals
colinstances = self.colinstances
tblfile, tblpath = self._v_file, self._v_pathname
# Look for the required variables first among the ones
# explicitly provided by the user, then among implicit columns,
# then among external variables (only if no explicit variables).
reqvars = {}
for var in exprvars:
# Get the value.
if uservars is not None and var in uservars:
val = uservars[var]
elif var in colinstances:
val = colinstances[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, 'pathname'): # non-nested column
if val.shape[1:] != ():
raise NotImplementedError(
"variable ``%s`` refers to "
"a multidimensional column, "
"not yet supported in conditions, sorry" % var)
if (val._table_file is not tblfile or
val._table_path != tblpath):
raise ValueError("variable ``%s`` refers to a column "
"which is not part of table ``%s``"
% (var, tblpath))
if val.dtype.str[1:] == 'u8':
raise NotImplementedError(
"variable ``%s`` refers to "
"a 64-bit unsigned integer column, "
"not yet supported in conditions, sorry; "
"please use regular Python selections" % var)
elif hasattr(val, '_v_colpathnames'): # nested column
raise TypeError(
"variable ``%s`` refers to a nested column, "
"not allowed in conditions" % var)
else: # only non-column values are converted to arrays
# XXX: not 100% sure about this
if isinstance(val, str):
val = np.asarray(val.encode('ascii'))
else:
val = np.asarray(val)
reqvars[var] = val
return reqvars
| (self, expression, uservars, depth=1) |
728,900 | tables.table | _save_buffered_rows | Update the indexes after a flushing of rows. | def _save_buffered_rows(self, wbufRA, lenrows):
"""Update the indexes after a flushing of rows."""
self._open_append(wbufRA)
self._append_records(lenrows)
self._close_append()
if self.indexed:
self._unsaved_indexedrows += lenrows
# The table caches for indexed queries are dirty now
self._dirtycache = True
if self.autoindex:
# Flush the unindexed rows
self.flush_rows_to_index(_lastrow=False)
else:
# All the columns are dirty now
self._mark_columns_as_dirty(self.colpathnames)
| (self, wbufRA, lenrows) |
728,901 | tables.table | _set_column_indexing | Mark the referred column as indexed or non-indexed. | def _set_column_indexing(self, colpathname, indexed):
"""Mark the referred column as indexed or non-indexed."""
colindexed = self.colindexed
isindexed, wasindexed = bool(indexed), colindexed[colpathname]
if isindexed == wasindexed:
return # indexing state is unchanged
# Changing the set of indexed columns invalidates the condition cache
self._condition_cache.clear()
colindexed[colpathname] = isindexed
self.indexed = max(colindexed.values()) # this is an OR :)
| (self, colpathname, indexed) |
728,902 | tables.table | _where | Low-level counterpart of `self.where()`. | def _where(self, condition, condvars, start=None, stop=None, step=None):
"""Low-level counterpart of `self.where()`."""
if profile:
tref = clock()
if profile:
show_stats("Entering table._where", tref)
# Adjust the slice to be used.
(start, stop, step) = self._process_range_read(start, stop, step)
if start >= stop: # empty range, reset conditions
self._use_index = False
self._where_condition = None
return iter([])
# Compile the condition and extract usable index conditions.
condvars = self._required_expr_vars(condition, condvars, depth=3)
compiled = self._compile_condition(condition, condvars)
# Can we use indexes?
if compiled.index_expressions:
chunkmap = _table__where_indexed(
self, compiled, condition, condvars, start, stop, step)
if not isinstance(chunkmap, np.ndarray):
# If it is not a NumPy array it should be an iterator
# Reset conditions
self._use_index = False
self._where_condition = None
# ...and return the iterator
return chunkmap
else:
chunkmap = None # default to an in-kernel query
args = [condvars[param] for param in compiled.parameters]
self._where_condition = (compiled.function, args, compiled.kwargs)
row = tableextension.Row(self)
if profile:
show_stats("Exiting table._where", tref)
return row._iter(start, stop, step, chunkmap=chunkmap)
| (self, condition, condvars, start=None, stop=None, step=None) |
728,903 | tables.table | append | Append a sequence of rows to the end of the table.
The rows argument may be any object which can be converted to
a structured array compliant with the table structure
(otherwise, a ValueError is raised). This includes NumPy
structured arrays, lists of tuples or array records, and a
string or Python buffer.
Examples
--------
::
import tables as tb
class Particle(tb.IsDescription):
name = tb.StringCol(16, pos=1) # 16-character String
lati = tb.IntCol(pos=2) # integer
longi = tb.IntCol(pos=3) # integer
pressure = tb.Float32Col(pos=4) # float (single-precision)
temperature = tb.FloatCol(pos=5) # double (double-precision)
fileh = tb.open_file('test4.h5', mode='w')
table = fileh.create_table(fileh.root, 'table', Particle,
"A table")
# Append several rows in only one call
table.append([("Particle: 10", 10, 0, 10 * 10, 10**2),
("Particle: 11", 11, -1, 11 * 11, 11**2),
("Particle: 12", 12, -2, 12 * 12, 12**2)])
fileh.close()
| def append(self, rows):
"""Append a sequence of rows to the end of the table.
The rows argument may be any object which can be converted to
a structured array compliant with the table structure
(otherwise, a ValueError is raised). This includes NumPy
structured arrays, lists of tuples or array records, and a
string or Python buffer.
Examples
--------
::
import tables as tb
class Particle(tb.IsDescription):
name = tb.StringCol(16, pos=1) # 16-character String
lati = tb.IntCol(pos=2) # integer
longi = tb.IntCol(pos=3) # integer
pressure = tb.Float32Col(pos=4) # float (single-precision)
temperature = tb.FloatCol(pos=5) # double (double-precision)
fileh = tb.open_file('test4.h5', mode='w')
table = fileh.create_table(fileh.root, 'table', Particle,
"A table")
# Append several rows in only one call
table.append([("Particle: 10", 10, 0, 10 * 10, 10**2),
("Particle: 11", 11, -1, 11 * 11, 11**2),
("Particle: 12", 12, -2, 12 * 12, 12**2)])
fileh.close()
"""
self._g_check_open()
self._v_file._check_writable()
if not self._chunked:
raise HDF5ExtError(
"You cannot append rows to a non-chunked table.", h5bt=False)
if (hasattr(rows, "dtype") and
not self.description._v_is_nested and
rows.dtype == self.dtype):
# Shortcut for compliant arrays
# (for some reason, not valid for nested types)
wbufRA = rows
else:
# Try to convert the object into a recarray compliant with table
try:
iflavor = flavor_of(rows)
if iflavor != 'python':
rows = array_as_internal(rows, iflavor)
# Works for Python structures and always copies the original,
# so the resulting object is safe for in-place conversion.
wbufRA = np.rec.array(rows, dtype=self._v_dtype)
except Exception as exc: # XXX
raise ValueError("rows parameter cannot be converted into a "
"recarray object compliant with table '%s'. "
"The error was: <%s>" % (str(self), exc))
lenrows = wbufRA.shape[0]
# If the number of rows to append is zero, don't do anything else
if lenrows > 0:
# Save write buffer to disk
self._save_buffered_rows(wbufRA, lenrows)
| (self, rows) |
728,904 | tables.table | append_where | Append rows fulfilling the condition to the dstTable table.
dstTable must be capable of taking the rows resulting from the query,
i.e. it must have columns with the expected names and compatible
types. The meaning of the other arguments is the same as in the
:meth:`Table.where` method.
The number of rows appended to dstTable is returned as a result.
.. versionchanged:: 3.0
The *whereAppend* method has been renamed into *append_where*.
| def append_where(self, dstTable, condition=None, condvars=None,
start=None, stop=None, step=None):
"""Append rows fulfilling the condition to the dstTable table.
dstTable must be capable of taking the rows resulting from the query,
i.e. it must have columns with the expected names and compatible
types. The meaning of the other arguments is the same as in the
:meth:`Table.where` method.
The number of rows appended to dstTable is returned as a result.
.. versionchanged:: 3.0
The *whereAppend* method has been renamed into *append_where*.
"""
self._g_check_open()
# Check that the destination file is not in read-only mode.
dstTable._v_file._check_writable()
# Row objects do not support nested columns, so we must iterate
# over the flat column paths. When rows support nesting,
# ``self.colnames`` can be directly iterated upon.
colNames = [colName for colName in self.colpathnames]
dstRow = dstTable.row
nrows = 0
if condition is not None:
srcRows = self._where(condition, condvars, start, stop, step)
else:
srcRows = self.iterrows(start, stop, step)
for srcRow in srcRows:
for colName in colNames:
dstRow[colName] = srcRow[colName]
dstRow.append()
nrows += 1
dstTable.flush()
return nrows
| (self, dstTable, condition=None, condvars=None, start=None, stop=None, step=None) |
728,906 | tables.table | col | Get a column from the table.
If a column called name exists in the table, it is read and returned as
a NumPy object. If it does not exist, a KeyError is raised.
Examples
--------
::
narray = table.col('var2')
That statement is equivalent to::
narray = table.read(field='var2')
Here you can see how this method can be used as a shorthand for the
:meth:`Table.read` method.
| def col(self, name):
"""Get a column from the table.
If a column called name exists in the table, it is read and returned as
a NumPy object. If it does not exist, a KeyError is raised.
Examples
--------
::
narray = table.col('var2')
That statement is equivalent to::
narray = table.read(field='var2')
Here you can see how this method can be used as a shorthand for the
:meth:`Table.read` method.
"""
return self.read(field=name)
| (self, name) |
728,907 | tables.table | copy | Copy this table and return the new one.
This method has the behavior and keywords described in
:meth:`Leaf.copy`. Moreover, it recognises the following additional
keyword arguments.
Parameters
----------
sortby
If specified, and sortby corresponds to a column with an index,
then the copy will be sorted by this index. If you want to ensure
a fully sorted order, the index must be a CSI one. A reverse
sorted copy can be achieved by specifying a negative value for the
step keyword. If sortby is omitted or None, the original table
order is used.
checkCSI
If true and a CSI index does not exist for the sortby column, an
error will be raised. If false (the default), it does nothing.
You can use this flag in order to explicitly check for the
existence of a CSI index.
propindexes
If true, the existing indexes in the source table are propagated
(created) to the new one. If false (the default), the indexes are
not propagated.
| def copy(self, newparent=None, newname=None, overwrite=False,
createparents=False, **kwargs):
"""Copy this table and return the new one.
This method has the behavior and keywords described in
:meth:`Leaf.copy`. Moreover, it recognises the following additional
keyword arguments.
Parameters
----------
sortby
If specified, and sortby corresponds to a column with an index,
then the copy will be sorted by this index. If you want to ensure
a fully sorted order, the index must be a CSI one. A reverse
sorted copy can be achieved by specifying a negative value for the
step keyword. If sortby is omitted or None, the original table
order is used.
checkCSI
If true and a CSI index does not exist for the sortby column, an
error will be raised. If false (the default), it does nothing.
You can use this flag in order to explicitly check for the
existence of a CSI index.
propindexes
If true, the existing indexes in the source table are propagated
(created) to the new one. If false (the default), the indexes are
not propagated.
"""
return super().copy(
newparent, newname, overwrite, createparents, **kwargs)
| (self, newparent=None, newname=None, overwrite=False, createparents=False, **kwargs) |
Subsets and Splits