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,909 | tables.table | flush | Flush the table buffers. | 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()
| (self) |
728,910 | tables.table | flush_rows_to_index | 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.
| 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
| (self, _lastrow=True) |
728,912 | tables.table | get_enum | 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.
| 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))
| (self, colname) |
728,913 | tables.table | get_where_list | 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.
| 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)
| (self, condition, condvars=None, sort=False, start=None, stop=None, step=None) |
728,915 | tables.table | iterrows | 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.
| 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)
| (self, start=None, stop=None, step=None) |
728,916 | tables.table | itersequence | Iterate over a sequence of row coordinates. | 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)
| (self, sequence) |
728,917 | tables.table | itersorted | 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.
| 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)
| (self, sortby, checkCSI=False, start=None, stop=None, step=None) |
728,918 | tables.table | modify_column | 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.
| 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)
| (self, start=None, stop=None, step=None, column=None, colname=None) |
728,919 | tables.table | modify_columns | 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.
| 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)
| (self, start=None, stop=None, step=None, columns=None, names=None) |
728,920 | tables.table | modify_coordinates | 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`.
| 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)
| (self, coords, rows) |
728,921 | tables.table | modify_rows | 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`.
| 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)
| (self, start=None, stop=None, step=None, rows=None) |
728,923 | tables.table | read | 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)
| 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)
| (self, start=None, stop=None, step=None, field=None, out=None) |
728,924 | tables.table | read_coordinates | 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.
| 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)
| (self, coords, field=None) |
728,925 | tables.table | read_sorted | 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.
| 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)
| (self, sortby, checkCSI=False, field=None, start=None, stop=None, step=None) |
728,926 | tables.table | read_where | 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.
| 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)
| (self, condition, condvars=None, field=None, start=None, stop=None, step=None) |
728,927 | tables.table | reindex | 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.
| 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)
| (self) |
728,928 | tables.table | reindex_dirty | 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).
| 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)
| (self) |
728,930 | tables.table | remove_row | 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)
| 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)
| (self, n) |
728,931 | tables.table | remove_rows | 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.
| 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)
| (self, start=None, stop=None, step=None) |
728,935 | tables.table | where | 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.
| 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)
| (self, condition, condvars=None, start=None, stop=None, step=None) |
728,936 | tables.table | will_query_use_indexing | 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.
| 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)
| (self, condition, condvars=None) |
728,937 | tables.atom | Time32Atom | Defines an atom of type time32. | class Time32Atom(TimeAtom):
"""Defines an atom of type time32."""
itemsize = 4
type = 'time32'
_defvalue = 0
def __init__(self, shape=(), dflt=_defvalue):
Atom.__init__(self, 'int32', shape, dflt)
| (shape=(), dflt=0) |
728,939 | tables.atom | __init__ | null | def __init__(self, shape=(), dflt=_defvalue):
Atom.__init__(self, 'int32', shape, dflt)
| (self, shape=(), dflt=0) |
728,945 | tables.description | Time32Col | 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 Time32Col
| (*args, **kwargs) |
728,953 | tables.atom | Time64Atom | Defines an atom of type time64. | class Time64Atom(TimeAtom):
"""Defines an atom of type time64."""
itemsize = 8
type = 'time64'
_defvalue = 0.0
def __init__(self, shape=(), dflt=_defvalue):
Atom.__init__(self, 'float64', shape, dflt)
| (shape=(), dflt=0.0) |
728,955 | tables.atom | __init__ | null | def __init__(self, shape=(), dflt=_defvalue):
Atom.__init__(self, 'float64', shape, dflt)
| (self, shape=(), dflt=0.0) |
728,961 | tables.description | Time64Col | 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 Time64Col
| (*args, **kwargs) |
728,969 | tables.atom | TimeAtom | Defines an atom of time type (time kind).
There are two distinct supported types of time: a 32 bit integer value and
a 64 bit floating point value. Both of them reflect the number of seconds
since the Unix epoch. This atom has the property of being stored using the
HDF5 time datatypes.
| class TimeAtom(Atom):
"""Defines an atom of time type (time kind).
There are two distinct supported types of time: a 32 bit integer value and
a 64 bit floating point value. Both of them reflect the number of seconds
since the Unix epoch. This atom has the property of being stored using the
HDF5 time datatypes.
"""
kind = 'time'
_deftype = 'time32'
_defvalue = 0
__init__ = _abstract_atom_init(_deftype, _defvalue)
| (itemsize=4, shape=(), dflt=0) |
728,977 | tables.description | TimeCol | 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 TimeCol
| (*args, **kwargs) |
728,985 | tables.atom | UInt16Atom | Defines an atom of type ``uint16``. | from tables.atom import UInt16Atom
| (shape=(), dflt=0) |
728,993 | tables.description | UInt16Col | 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 UInt16Col
| (*args, **kwargs) |
729,001 | tables.atom | UInt32Atom | Defines an atom of type ``uint32``. | from tables.atom import UInt32Atom
| (shape=(), dflt=0) |
729,009 | tables.description | UInt32Col | 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 UInt32Col
| (*args, **kwargs) |
729,017 | tables.atom | UInt64Atom | Defines an atom of type ``uint64``. | from tables.atom import UInt64Atom
| (shape=(), dflt=0) |
729,025 | tables.description | UInt64Col | 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 UInt64Col
| (*args, **kwargs) |
729,033 | tables.atom | UInt8Atom | Defines an atom of type ``uint8``. | from tables.atom import UInt8Atom
| (shape=(), dflt=0) |
729,041 | tables.description | UInt8Col | 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 UInt8Col
| (*args, **kwargs) |
729,049 | tables.atom | UIntAtom | Defines an atom of an unsigned integral type (uint kind). | class UIntAtom(Atom):
"""Defines an atom of an unsigned integral type (uint kind)."""
kind = 'uint'
signed = False
_deftype = 'uint32'
_defvalue = 0
__init__ = _abstract_atom_init(_deftype, _defvalue)
| (itemsize=4, shape=(), dflt=0) |
729,057 | tables.description | UIntCol | 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 UIntCol
| (*args, **kwargs) |
729,065 | tables.unimplemented | UnImplemented | This class represents datasets not supported by PyTables in an HDF5
file.
When reading a generic HDF5 file (i.e. one that has not been created with
PyTables, but with some other HDF5 library based tool), chances are that
the specific combination of datatypes or dataspaces in some dataset might
not be supported by PyTables yet. In such a case, this dataset will be
mapped into an UnImplemented instance and the user will still be able to
access the complete object tree of the generic HDF5 file. The user will
also be able to *read and write the attributes* of the dataset, *access
some of its metadata*, and perform *certain hierarchy manipulation
operations* like deleting or moving (but not copying) the node. Of course,
the user will not be able to read the actual data on it.
This is an elegant way to allow users to work with generic HDF5 files
despite the fact that some of its datasets are not supported by
PyTables. However, if you are really interested in having full access to an
unimplemented dataset, please get in contact with the developer team.
This class does not have any public instance variables or methods, except
those inherited from the Leaf class (see :ref:`LeafClassDescr`).
| class UnImplemented(hdf5extension.UnImplemented, Leaf):
"""This class represents datasets not supported by PyTables in an HDF5
file.
When reading a generic HDF5 file (i.e. one that has not been created with
PyTables, but with some other HDF5 library based tool), chances are that
the specific combination of datatypes or dataspaces in some dataset might
not be supported by PyTables yet. In such a case, this dataset will be
mapped into an UnImplemented instance and the user will still be able to
access the complete object tree of the generic HDF5 file. The user will
also be able to *read and write the attributes* of the dataset, *access
some of its metadata*, and perform *certain hierarchy manipulation
operations* like deleting or moving (but not copying) the node. Of course,
the user will not be able to read the actual data on it.
This is an elegant way to allow users to work with generic HDF5 files
despite the fact that some of its datasets are not supported by
PyTables. However, if you are really interested in having full access to an
unimplemented dataset, please get in contact with the developer team.
This class does not have any public instance variables or methods, except
those inherited from the Leaf class (see :ref:`LeafClassDescr`).
"""
# Class identifier.
_c_classid = 'UNIMPLEMENTED'
def __init__(self, parentnode, name):
"""Create the `UnImplemented` instance."""
# UnImplemented objects always come from opening an existing node
# (they can not be created).
self._v_new = False
"""Is this the first time the node has been created?"""
self.nrows = SizeType(0)
"""The length of the first dimension of the data."""
self.shape = (SizeType(0),)
"""The shape of the stored data."""
self.byteorder = None
"""The endianness of data in memory ('big', 'little' or
'irrelevant')."""
super().__init__(parentnode, name)
def _g_open(self):
(self.shape, self.byteorder, object_id) = self._open_unimplemented()
try:
self.nrows = SizeType(self.shape[0])
except IndexError:
self.nrows = SizeType(0)
return object_id
def _g_copy(self, newparent, newname, recursive, _log=True, **kwargs):
"""Do nothing.
This method does nothing, but a ``UserWarning`` is issued.
Please note that this method *does not return a new node*, but
``None``.
"""
warnings.warn(
"UnImplemented node %r does not know how to copy itself; skipping"
% (self._v_pathname,))
return None # Can you see it?
def _f_copy(self, newparent=None, newname=None,
overwrite=False, recursive=False, createparents=False,
**kwargs):
"""Do nothing.
This method does nothing, since `UnImplemented` nodes can not
be copied. However, a ``UserWarning`` is issued. Please note
that this method *does not return a new node*, but ``None``.
"""
# This also does nothing but warn.
self._g_copy(newparent, newname, recursive, **kwargs)
return None # Can you see it?
def __repr__(self):
return """{}
NOTE: <The UnImplemented object represents a PyTables unimplemented
dataset present in the '{}' HDF5 file. If you want to see this
kind of HDF5 dataset implemented in PyTables, please contact the
developers.>
""".format(str(self), self._v_file.filename)
| (parentnode, name) |
729,067 | tables.unimplemented | __init__ | Create the `UnImplemented` instance. | def __init__(self, parentnode, name):
"""Create the `UnImplemented` instance."""
# UnImplemented objects always come from opening an existing node
# (they can not be created).
self._v_new = False
"""Is this the first time the node has been created?"""
self.nrows = SizeType(0)
"""The length of the first dimension of the data."""
self.shape = (SizeType(0),)
"""The shape of the stored data."""
self.byteorder = None
"""The endianness of data in memory ('big', 'little' or
'irrelevant')."""
super().__init__(parentnode, name)
| (self, parentnode, name) |
729,069 | tables.unimplemented | __repr__ | null | """Here is defined the UnImplemented class."""
import warnings
from . import hdf5extension
from .utils import SizeType
from .node import Node
from .leaf import Leaf
class UnImplemented(hdf5extension.UnImplemented, Leaf):
"""This class represents datasets not supported by PyTables in an HDF5
file.
When reading a generic HDF5 file (i.e. one that has not been created with
PyTables, but with some other HDF5 library based tool), chances are that
the specific combination of datatypes or dataspaces in some dataset might
not be supported by PyTables yet. In such a case, this dataset will be
mapped into an UnImplemented instance and the user will still be able to
access the complete object tree of the generic HDF5 file. The user will
also be able to *read and write the attributes* of the dataset, *access
some of its metadata*, and perform *certain hierarchy manipulation
operations* like deleting or moving (but not copying) the node. Of course,
the user will not be able to read the actual data on it.
This is an elegant way to allow users to work with generic HDF5 files
despite the fact that some of its datasets are not supported by
PyTables. However, if you are really interested in having full access to an
unimplemented dataset, please get in contact with the developer team.
This class does not have any public instance variables or methods, except
those inherited from the Leaf class (see :ref:`LeafClassDescr`).
"""
# Class identifier.
_c_classid = 'UNIMPLEMENTED'
def __init__(self, parentnode, name):
"""Create the `UnImplemented` instance."""
# UnImplemented objects always come from opening an existing node
# (they can not be created).
self._v_new = False
"""Is this the first time the node has been created?"""
self.nrows = SizeType(0)
"""The length of the first dimension of the data."""
self.shape = (SizeType(0),)
"""The shape of the stored data."""
self.byteorder = None
"""The endianness of data in memory ('big', 'little' or
'irrelevant')."""
super().__init__(parentnode, name)
def _g_open(self):
(self.shape, self.byteorder, object_id) = self._open_unimplemented()
try:
self.nrows = SizeType(self.shape[0])
except IndexError:
self.nrows = SizeType(0)
return object_id
def _g_copy(self, newparent, newname, recursive, _log=True, **kwargs):
"""Do nothing.
This method does nothing, but a ``UserWarning`` is issued.
Please note that this method *does not return a new node*, but
``None``.
"""
warnings.warn(
"UnImplemented node %r does not know how to copy itself; skipping"
% (self._v_pathname,))
return None # Can you see it?
def _f_copy(self, newparent=None, newname=None,
overwrite=False, recursive=False, createparents=False,
**kwargs):
"""Do nothing.
This method does nothing, since `UnImplemented` nodes can not
be copied. However, a ``UserWarning`` is issued. Please note
that this method *does not return a new node*, but ``None``.
"""
# This also does nothing but warn.
self._g_copy(newparent, newname, recursive, **kwargs)
return None # Can you see it?
def __repr__(self):
return """{}
NOTE: <The UnImplemented object represents a PyTables unimplemented
dataset present in the '{}' HDF5 file. If you want to see this
kind of HDF5 dataset implemented in PyTables, please contact the
developers.>
""".format(str(self), self._v_file.filename)
| (self) |
729,074 | tables.unimplemented | _f_copy | Do nothing.
This method does nothing, since `UnImplemented` nodes can not
be copied. However, a ``UserWarning`` is issued. Please note
that this method *does not return a new node*, but ``None``.
| def _f_copy(self, newparent=None, newname=None,
overwrite=False, recursive=False, createparents=False,
**kwargs):
"""Do nothing.
This method does nothing, since `UnImplemented` nodes can not
be copied. However, a ``UserWarning`` is issued. Please note
that this method *does not return a new node*, but ``None``.
"""
# This also does nothing but warn.
self._g_copy(newparent, newname, recursive, **kwargs)
return None # Can you see it?
| (self, newparent=None, newname=None, overwrite=False, recursive=False, createparents=False, **kwargs) |
729,086 | tables.unimplemented | _g_copy | Do nothing.
This method does nothing, but a ``UserWarning`` is issued.
Please note that this method *does not return a new node*, but
``None``.
| def _g_copy(self, newparent, newname, recursive, _log=True, **kwargs):
"""Do nothing.
This method does nothing, but a ``UserWarning`` is issued.
Please note that this method *does not return a new node*, but
``None``.
"""
warnings.warn(
"UnImplemented node %r does not know how to copy itself; skipping"
% (self._v_pathname,))
return None # Can you see it?
| (self, newparent, newname, recursive, _log=True, **kwargs) |
729,097 | tables.unimplemented | _g_open | null | def _g_open(self):
(self.shape, self.byteorder, object_id) = self._open_unimplemented()
try:
self.nrows = SizeType(self.shape[0])
except IndexError:
self.nrows = SizeType(0)
return object_id
| (self) |
729,120 | tables.exceptions | UnclosedFileWarning | Warning raised when there are still open files at program exit
Pytables will close remaining open files at exit, but raise
this warning.
| class UnclosedFileWarning(Warning):
"""Warning raised when there are still open files at program exit
Pytables will close remaining open files at exit, but raise
this warning.
"""
pass
| null |
729,121 | tables.exceptions | UndoRedoError | Problems with doing/redoing actions with Undo/Redo feature.
This exception indicates a problem related to the Undo/Redo
mechanism, such as trying to undo or redo actions with this
mechanism disabled, or going to a nonexistent mark.
| class UndoRedoError(Exception):
"""Problems with doing/redoing actions with Undo/Redo feature.
This exception indicates a problem related to the Undo/Redo
mechanism, such as trying to undo or redo actions with this
mechanism disabled, or going to a nonexistent mark.
"""
pass
| null |
729,122 | tables.exceptions | UndoRedoWarning | Issued when an action not supporting Undo/Redo is run.
This warning is only shown when the Undo/Redo mechanism is enabled.
| class UndoRedoWarning(Warning):
"""Issued when an action not supporting Undo/Redo is run.
This warning is only shown when the Undo/Redo mechanism is enabled.
"""
pass
| null |
729,123 | tables.unimplemented | Unknown | This class represents nodes reported as *unknown* by the underlying
HDF5 library.
This class does not have any public instance variables or methods, except
those inherited from the Node class.
| class Unknown(Node):
"""This class represents nodes reported as *unknown* by the underlying
HDF5 library.
This class does not have any public instance variables or methods, except
those inherited from the Node class.
"""
# Class identifier
_c_classid = 'UNKNOWN'
def __init__(self, parentnode, name):
"""Create the `Unknown` instance."""
self._v_new = False
super().__init__(parentnode, name)
def _g_new(self, parentnode, name, init=False):
pass
def _g_open(self):
return 0
def _g_copy(self, newparent, newname, recursive, _log=True, **kwargs):
# Silently avoid doing copies of unknown nodes
return None
def _g_delete(self, parent):
pass
def __str__(self):
pathname = self._v_pathname
classname = self.__class__.__name__
return f"{pathname} ({classname})"
def __repr__(self):
return f"""{self!s}
NOTE: <The Unknown object represents a node which is reported as
unknown by the underlying HDF5 library, but that might be
supported in more recent HDF5 versions.>
"""
| (parentnode, name) |
729,125 | tables.unimplemented | __init__ | Create the `Unknown` instance. | def __init__(self, parentnode, name):
"""Create the `Unknown` instance."""
self._v_new = False
super().__init__(parentnode, name)
| (self, parentnode, name) |
729,141 | tables.unimplemented | _g_copy | null | def _g_copy(self, newparent, newname, recursive, _log=True, **kwargs):
# Silently avoid doing copies of unknown nodes
return None
| (self, newparent, newname, recursive, _log=True, **kwargs) |
729,145 | tables.unimplemented | _g_delete | null | def _g_delete(self, parent):
pass
| (self, parent) |
729,152 | tables.unimplemented | _g_new | null | def _g_new(self, parentnode, name, init=False):
pass
| (self, parentnode, name, init=False) |
729,153 | tables.unimplemented | _g_open | null | def _g_open(self):
return 0
| (self) |
729,162 | tables.vlarray | VLArray | This class represents variable length (ragged) arrays in an HDF5 file.
Instances of this class represent array objects in the object tree
with the property that their rows can have a *variable* number of
homogeneous elements, called *atoms*. Like Table datasets (see
:ref:`TableClassDescr`), variable length arrays can have only one
dimension, and the elements (atoms) of their rows can be fully
multidimensional.
When reading a range of rows from a VLArray, you will *always* get
a Python list of objects of the current flavor (each of them for a
row), which may have different lengths.
This class provides methods to write or read data to or from
variable length array objects in the file. Note that it also
inherits all the public attributes and methods that Leaf (see
:ref:`LeafClassDescr`) already provides.
.. note::
VLArray objects also support compression although compression
is only performed on the data structures used internally by
the HDF5 to take references of the location of the variable
length data. Data itself (the raw data) are not compressed
or filtered.
Please refer to the `VLTypes Technical Note
<https://support.hdfgroup.org/HDF5/doc/TechNotes/VLTypes.html>`_
for more details on the topic.
Parameters
----------
parentnode
The parent :class:`Group` object.
name : str
The name of this node in its parent group.
atom
An `Atom` instance representing the *type* and *shape* of the atomic
objects to be saved.
title
A description for this node (it sets the ``TITLE`` HDF5 attribute on
disk).
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 row elements that will
be added to the growable dimension in the `VLArray` node.
If not provided, the default value is ``EXPECTED_ROWS_VLARRAY``
(see ``tables/parameters.py``). If you plan to create either
a much smaller or a much bigger `VLArray` try providing a guess;
this will optimize the HDF5 B-Tree creation and management
process time and the amount of memory used.
.. versionadded:: 3.0
chunkshape
The shape of the data chunk to be read or written in a single HDF5 I/O
operation. Filters are applied to those chunks of data. The
dimensionality of `chunkshape` must be 1. If ``None``, a sensible
value is calculated (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.
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
.. versionchanged:: 3.0
*parentNode* renamed into *parentnode*.
.. versionchanged:: 3.0
The *expectedsizeinMB* parameter has been replaced by *expectedrows*.
Examples
--------
See below a small example of the use of the VLArray class. The code is
available in :file:`examples/vlarray1.py`::
import numpy as np
import tables as tb
# Create a VLArray:
fileh = tb.open_file('vlarray1.h5', mode='w')
vlarray = fileh.create_vlarray(
fileh.root,
'vlarray1',
tb.Int32Atom(shape=()),
"ragged array of ints",
filters=tb.Filters(1))
# Append some (variable length) rows:
vlarray.append(np.array([5, 6]))
vlarray.append(np.array([5, 6, 7]))
vlarray.append([5, 6, 9, 8])
# Now, read it through an iterator:
print('-->', vlarray.title)
for x in vlarray:
print('%s[%d]--> %s' % (vlarray.name, vlarray.nrow, x))
# Now, do the same with native Python strings.
vlarray2 = fileh.create_vlarray(
fileh.root,
'vlarray2',
tb.StringAtom(itemsize=2),
"ragged array of strings",
filters=tb.Filters(1))
vlarray2.flavor = 'python'
# Append some (variable length) rows:
print('-->', vlarray2.title)
vlarray2.append(['5', '66'])
vlarray2.append(['5', '6', '77'])
vlarray2.append(['5', '6', '9', '88'])
# Now, read it through an iterator:
for x in vlarray2:
print('%s[%d]--> %s' % (vlarray2.name, vlarray2.nrow, x))
# Close the file.
fileh.close()
The output for the previous script is something like::
--> ragged array of ints
vlarray1[0]--> [5 6]
vlarray1[1]--> [5 6 7]
vlarray1[2]--> [5 6 9 8]
--> ragged array of strings
vlarray2[0]--> ['5', '66']
vlarray2[1]--> ['5', '6', '77']
vlarray2[2]--> ['5', '6', '9', '88']
.. rubric:: VLArray attributes
The instance variables below are provided in addition to those in
Leaf (see :ref:`LeafClassDescr`).
.. attribute:: atom
An Atom (see :ref:`AtomClassDescr`)
instance representing the *type* and
*shape* of the atomic objects to be
saved. You may use a *pseudo-atom* for
storing a serialized object or variable length string per row.
.. attribute:: flavor
The type of data object read from this leaf.
Please note that when reading several rows of VLArray data,
the flavor only applies to the *components* of the returned
Python list, not to the list itself.
.. attribute:: nrow
On iterators, this is the index of the current row.
.. attribute:: nrows
The current number of rows in the array.
.. attribute:: extdim
The index of the enlargeable dimension (always 0 for vlarrays).
| class VLArray(hdf5extension.VLArray, Leaf):
"""This class represents variable length (ragged) arrays in an HDF5 file.
Instances of this class represent array objects in the object tree
with the property that their rows can have a *variable* number of
homogeneous elements, called *atoms*. Like Table datasets (see
:ref:`TableClassDescr`), variable length arrays can have only one
dimension, and the elements (atoms) of their rows can be fully
multidimensional.
When reading a range of rows from a VLArray, you will *always* get
a Python list of objects of the current flavor (each of them for a
row), which may have different lengths.
This class provides methods to write or read data to or from
variable length array objects in the file. Note that it also
inherits all the public attributes and methods that Leaf (see
:ref:`LeafClassDescr`) already provides.
.. note::
VLArray objects also support compression although compression
is only performed on the data structures used internally by
the HDF5 to take references of the location of the variable
length data. Data itself (the raw data) are not compressed
or filtered.
Please refer to the `VLTypes Technical Note
<https://support.hdfgroup.org/HDF5/doc/TechNotes/VLTypes.html>`_
for more details on the topic.
Parameters
----------
parentnode
The parent :class:`Group` object.
name : str
The name of this node in its parent group.
atom
An `Atom` instance representing the *type* and *shape* of the atomic
objects to be saved.
title
A description for this node (it sets the ``TITLE`` HDF5 attribute on
disk).
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 row elements that will
be added to the growable dimension in the `VLArray` node.
If not provided, the default value is ``EXPECTED_ROWS_VLARRAY``
(see ``tables/parameters.py``). If you plan to create either
a much smaller or a much bigger `VLArray` try providing a guess;
this will optimize the HDF5 B-Tree creation and management
process time and the amount of memory used.
.. versionadded:: 3.0
chunkshape
The shape of the data chunk to be read or written in a single HDF5 I/O
operation. Filters are applied to those chunks of data. The
dimensionality of `chunkshape` must be 1. If ``None``, a sensible
value is calculated (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.
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
.. versionchanged:: 3.0
*parentNode* renamed into *parentnode*.
.. versionchanged:: 3.0
The *expectedsizeinMB* parameter has been replaced by *expectedrows*.
Examples
--------
See below a small example of the use of the VLArray class. The code is
available in :file:`examples/vlarray1.py`::
import numpy as np
import tables as tb
# Create a VLArray:
fileh = tb.open_file('vlarray1.h5', mode='w')
vlarray = fileh.create_vlarray(
fileh.root,
'vlarray1',
tb.Int32Atom(shape=()),
"ragged array of ints",
filters=tb.Filters(1))
# Append some (variable length) rows:
vlarray.append(np.array([5, 6]))
vlarray.append(np.array([5, 6, 7]))
vlarray.append([5, 6, 9, 8])
# Now, read it through an iterator:
print('-->', vlarray.title)
for x in vlarray:
print('%s[%d]--> %s' % (vlarray.name, vlarray.nrow, x))
# Now, do the same with native Python strings.
vlarray2 = fileh.create_vlarray(
fileh.root,
'vlarray2',
tb.StringAtom(itemsize=2),
"ragged array of strings",
filters=tb.Filters(1))
vlarray2.flavor = 'python'
# Append some (variable length) rows:
print('-->', vlarray2.title)
vlarray2.append(['5', '66'])
vlarray2.append(['5', '6', '77'])
vlarray2.append(['5', '6', '9', '88'])
# Now, read it through an iterator:
for x in vlarray2:
print('%s[%d]--> %s' % (vlarray2.name, vlarray2.nrow, x))
# Close the file.
fileh.close()
The output for the previous script is something like::
--> ragged array of ints
vlarray1[0]--> [5 6]
vlarray1[1]--> [5 6 7]
vlarray1[2]--> [5 6 9 8]
--> ragged array of strings
vlarray2[0]--> ['5', '66']
vlarray2[1]--> ['5', '6', '77']
vlarray2[2]--> ['5', '6', '9', '88']
.. rubric:: VLArray attributes
The instance variables below are provided in addition to those in
Leaf (see :ref:`LeafClassDescr`).
.. attribute:: atom
An Atom (see :ref:`AtomClassDescr`)
instance representing the *type* and
*shape* of the atomic objects to be
saved. You may use a *pseudo-atom* for
storing a serialized object or variable length string per row.
.. attribute:: flavor
The type of data object read from this leaf.
Please note that when reading several rows of VLArray data,
the flavor only applies to the *components* of the returned
Python list, not to the list itself.
.. attribute:: nrow
On iterators, this is the index of the current row.
.. attribute:: nrows
The current number of rows in the array.
.. attribute:: extdim
The index of the enlargeable dimension (always 0 for vlarrays).
"""
# Class identifier.
_c_classid = 'VLARRAY'
@lazyattr
def dtype(self):
"""The NumPy ``dtype`` that most closely matches this array."""
return self.atom.dtype
@property
def shape(self):
"""The shape of the stored array."""
return (self.nrows,)
@property
def size_on_disk(self):
"""
The HDF5 library does not include a function to determine size_on_disk
for variable-length arrays. Accessing this attribute will raise a
NotImplementedError.
"""
raise NotImplementedError('size_on_disk not implemented for VLArrays')
@property
def size_in_memory(self):
"""
The size of this array's data in bytes when it is fully loaded
into memory.
.. note::
When data is stored in a VLArray using the ObjectAtom type,
it is first serialized using pickle, and then converted to
a NumPy array suitable for storage in an HDF5 file.
This attribute will return the size of that NumPy
representation. If you wish to know the size of the Python
objects after they are loaded from disk, you can use this
`ActiveState recipe
<http://code.activestate.com/recipes/577504/>`_.
"""
return self._get_memory_size()
def __init__(self, parentnode, name, atom=None, title="",
filters=None, expectedrows=None,
chunkshape=None, byteorder=None,
_log=True, track_times=True):
self._v_version = None
"""The object version of this array."""
self._v_new = new = atom 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 array."""
if expectedrows is None:
expectedrows = parentnode._v_file.params['EXPECTED_ROWS_VLARRAY']
self._v_expectedrows = expectedrows
"""The expected number of rows to be stored in the array.
.. versionadded:: 3.0
"""
self._v_chunkshape = None
"""Private storage for the `chunkshape` property of Leaf."""
# Miscellaneous iteration rubbish.
self._start = None
"""Starting row for the current iteration."""
self._stop = None
"""Stopping row for the current iteration."""
self._step = None
"""Step size for the current iteration."""
self._nrowsread = None
"""Number of rows read up to the current state of iteration."""
self._startb = None
"""Starting row for current buffer."""
self._stopb = None
"""Stopping row for current buffer. """
self._row = None
"""Current row in iterators (sentinel)."""
self._init = False
"""Whether we are in the middle of an iteration or not (sentinel)."""
self.listarr = None
"""Current buffer in iterators."""
# Documented (*public*) attributes.
self.atom = atom
"""
An Atom (see :ref:`AtomClassDescr`) instance representing the
*type* and *shape* of the atomic objects to be saved. You may
use a *pseudo-atom* for storing a serialized object or
variable length string per row.
"""
self.nrow = None
"""On iterators, this is the index of the current row."""
self.nrows = None
"""The current number of rows in the array."""
self.extdim = 0 # VLArray only have one dimension currently
"""The index of the enlargeable dimension (always 0 for vlarrays)."""
# 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):
super()._g_post_init_hook()
self.nrowsinbuf = 100 # maybe enough for most applications
# This is too specific for moving it into Leaf
def _calc_chunkshape(self, expectedrows):
"""Calculate the size for the HDF5 chunk."""
# For computing the chunkshape for HDF5 VL types, we have to
# choose the itemsize of the *each* element of the atom and
# not the size of the entire atom. I don't know why this
# should be like this, perhaps I should report this to the
# HDF5 list.
# F. Alted 2006-11-23
# elemsize = self.atom.atomsize()
elemsize = self._basesize
# AV 2013-05-03
# This is just a quick workaround tha allows to change the API for
# PyTables 3.0 release and remove the expected_mb parameter.
# The algorithm for computing the chunkshape should be rewritten as
# requested by gh-35.
expected_mb = expectedrows * elemsize / 1024 ** 2
chunksize = calc_chunksize(expected_mb)
# Set the chunkshape
chunkshape = chunksize // elemsize
# Safeguard against itemsizes being extremely large
if chunkshape == 0:
chunkshape = 1
return (SizeType(chunkshape),)
def _g_create(self):
"""Create a variable length array (ragged array)."""
atom = self.atom
self._v_version = obversion
# Check for zero dims in atom shape (not allowed in VLArrays)
zerodims = np.sum(np.array(atom.shape) == 0)
if zerodims > 0:
raise ValueError("When creating VLArrays, none of the dimensions "
"of the Atom instance can be zero.")
if not hasattr(atom, 'size'): # it is a pseudo-atom
self._atomicdtype = atom.base.dtype
self._atomicsize = atom.base.size
self._basesize = atom.base.itemsize
else:
self._atomicdtype = atom.dtype
self._atomicsize = atom.size
self._basesize = atom.itemsize
self._atomictype = atom.type
self._atomicshape = atom.shape
# Compute the optimal chunkshape, if needed
if self._v_chunkshape is None:
self._v_chunkshape = self._calc_chunkshape(self._v_expectedrows)
self.nrows = SizeType(0) # No rows at creation time
# Correct the byteorder if needed
if self.byteorder is None:
self.byteorder = correct_byteorder(atom.type, sys.byteorder)
# After creating the vlarray, ``self._v_objectid`` needs to be
# set because it is needed for setting attributes afterwards.
self._v_objectid = self._create_array(self._v_new_title)
# Add an attribute in case we have a pseudo-atom so that we
# can retrieve the proper class after a re-opening operation.
if not hasattr(atom, 'size'): # it is a pseudo-atom
self.attrs.PSEUDOATOM = atom.kind
return self._v_objectid
def _g_open(self):
"""Get the metadata info for an array in file."""
self._v_objectid, self.nrows, self._v_chunkshape, atom = \
self._open_array()
# Check if the atom can be a PseudoAtom
if "PSEUDOATOM" in self.attrs:
kind = self.attrs.PSEUDOATOM
if kind == 'vlstring':
atom = VLStringAtom()
elif kind == 'vlunicode':
atom = VLUnicodeAtom()
elif kind == 'object':
atom = ObjectAtom()
else:
raise ValueError(
"pseudo-atom name ``%s`` not known." % kind)
elif self._v_file.format_version[:1] == "1":
flavor1x = self.attrs.FLAVOR
if flavor1x == "VLString":
atom = VLStringAtom()
elif flavor1x == "Object":
atom = ObjectAtom()
self.atom = atom
return self._v_objectid
def _getnobjects(self, nparr):
"""Return the number of objects in a NumPy array."""
# Check for zero dimensionality array
zerodims = np.sum(np.array(nparr.shape) == 0)
if zerodims > 0:
# No objects to be added
return 0
shape = nparr.shape
atom_shape = self.atom.shape
shapelen = len(nparr.shape)
if isinstance(atom_shape, tuple):
atomshapelen = len(self.atom.shape)
else:
atom_shape = (self.atom.shape,)
atomshapelen = 1
diflen = shapelen - atomshapelen
if shape == atom_shape:
nobjects = 1
elif (diflen == 1 and shape[diflen:] == atom_shape):
# Check if the leading dimensions are all ones
# if shape[:diflen-1] == (1,)*(diflen-1):
# nobjects = shape[diflen-1]
# shape = shape[diflen:]
# It's better to accept only inputs with the exact dimensionality
# i.e. a dimensionality only 1 element larger than atom
nobjects = shape[0]
shape = shape[1:]
elif atom_shape == (1,) and shapelen == 1:
# Case where shape = (N,) and shape_atom = 1 or (1,)
nobjects = shape[0]
else:
raise ValueError("The object '%s' is composed of elements with "
"shape '%s', which is not compatible with the "
"atom shape ('%s')." % (nparr, shape, atom_shape))
return nobjects
def get_enum(self):
"""Get the enumerated type associated with this array.
If this array 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 self.atom.kind != 'enum':
raise TypeError("array ``%s`` is not of an enumerated type"
% self._v_pathname)
return self.atom.enum
def append(self, sequence):
"""Add a sequence of data to the end of the dataset.
This method appends the objects in the sequence to a *single row* in
this array. The type and shape of individual objects must be compliant
with the atoms in the array. In the case of serialized objects and
variable length strings, the object or string to append is itself the
sequence.
"""
self._g_check_open()
self._v_file._check_writable()
# Prepare the sequence to convert it into a NumPy object
atom = self.atom
if not hasattr(atom, 'size'): # it is a pseudo-atom
sequence = atom.toarray(sequence)
statom = atom.base
else:
try: # fastest check in most cases
len(sequence)
except TypeError:
raise TypeError("argument is not a sequence")
statom = atom
if len(sequence) > 0:
# The sequence needs to be copied to make the operation safe
# to in-place conversion.
nparr = convert_to_np_atom2(sequence, statom)
nobjects = self._getnobjects(nparr)
else:
nobjects = 0
nparr = None
self._append(nparr, nobjects)
self.nrows += 1
def iterrows(self, start=None, stop=None, step=None):
"""Iterate over the rows of the array.
This method returns an iterator yielding an object of the current
flavor for each selected row in the array.
If a range is not supplied, *all the rows* in the array are iterated
upon. You can also use the :meth:`VLArray.__iter__` special method for
that purpose. If you only want to iterate over a given *range of rows*
in the array, you may use the start, stop and step parameters.
Examples
--------
::
for row in vlarray.iterrows(step=4):
print('%s[%d]--> %s' % (vlarray.name, vlarray.nrow, row))
.. versionchanged:: 3.0
If the *start* parameter is provided and *stop* is None then the
array is iterated from *start* to the last line.
In PyTables < 3.0 only one element was returned.
"""
(self._start, self._stop, self._step) = self._process_range(
start, stop, step)
self._init_loop()
return self
def __iter__(self):
"""Iterate over the rows of the array.
This is equivalent to calling :meth:`VLArray.iterrows` with default
arguments, i.e. it iterates over *all the rows* in the array.
Examples
--------
::
result = [row for row in vlarray]
Which is equivalent to::
result = [row for row in vlarray.iterrows()]
"""
if not self._init:
# If the iterator is called directly, assign default variables
self._start = 0
self._stop = self.nrows
self._step = 1
# and initialize the loop
self._init_loop()
return self
def _init_loop(self):
"""Initialization for the __iter__ iterator."""
self._nrowsread = self._start
self._startb = self._start
self._row = -1 # Sentinel
self._init = True # Sentinel
self.nrow = SizeType(self._start - self._step) # row number
def __next__(self):
"""Get the next element of the array during an iteration.
The element is returned as a list of objects of the current
flavor.
"""
if self._nrowsread >= self._stop:
self._init = False
raise StopIteration # end of iteration
else:
# Read a chunk of rows
if self._row + 1 >= self.nrowsinbuf or self._row < 0:
self._stopb = self._startb + self._step * self.nrowsinbuf
self.listarr = self.read(self._startb, self._stopb, self._step)
self._row = -1
self._startb = self._stopb
self._row += 1
self.nrow += self._step
self._nrowsread += self._step
return self.listarr[self._row]
def __getitem__(self, key):
"""Get a row or a range of rows from the array.
If key argument is an integer, the corresponding array row is returned
as an object of the current flavor. If key is a slice, the range of
rows determined by it is returned as a list of objects 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 array has.
Examples
--------
::
a_row = vlarray[4]
a_list = vlarray[4:1000:2]
a_list2 = vlarray[[0,2]] # get list of coords
a_list3 = vlarray[[0,-2]] # negative values accepted
a_list4 = vlarray[np.array([True,...,False])] # array of bools
"""
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):
coords = self._point_selection(key)
return self._read_coordinates(coords)
else:
raise IndexError(f"Invalid index or slice: {key!r}")
def _assign_values(self, coords, values):
"""Assign the `values` to the positions stated in `coords`."""
for nrow, value in zip(coords, values):
if nrow >= self.nrows:
raise IndexError("First index out of range")
if nrow < 0:
# To support negative values
nrow += self.nrows
object_ = value
# Prepare the object to convert it into a NumPy object
atom = self.atom
if not hasattr(atom, 'size'): # it is a pseudo-atom
object_ = atom.toarray(object_)
statom = atom.base
else:
statom = atom
value = convert_to_np_atom(object_, statom)
nobjects = self._getnobjects(value)
# Get the previous value
nrow = idx2long(
nrow) # To convert any possible numpy scalar value
nparr = self._read_array(nrow, nrow + 1, 1)[0]
nobjects = len(nparr)
if len(value) > nobjects:
raise ValueError("Length of value (%s) is larger than number "
"of elements in row (%s)" % (len(value),
nobjects))
try:
nparr[:] = value
except Exception as exc: # XXX
raise ValueError("Value parameter:\n'%r'\n"
"cannot be converted into an array object "
"compliant vlarray[%s] row: \n'%r'\n"
"The error was: <%s>" % (value, nrow,
nparr[:], exc))
if nparr.size > 0:
self._modify(nrow, nparr, nobjects)
def __setitem__(self, key, value):
"""Set a row, or set of rows, in the array.
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
of rows 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.
.. note::
When updating the rows of a VLArray object which uses a
pseudo-atom, there is a problem: you can only update values
with *exactly* the same size in bytes than the original row.
This is very difficult to meet with object pseudo-atoms,
because :mod:`pickle` applied on a Python object does not
guarantee to return the same number of bytes than over another
object, even if they are of the same class.
This effectively limits the kinds of objects than can be
updated in variable-length arrays.
Examples
--------
::
vlarray[0] = vlarray[0] * 2 + 3
vlarray[99] = arange(96) * 2 + 3
# Negative values for the index are supported.
vlarray[-99] = vlarray[5] * 2 + 3
vlarray[1:30:2] = list_of_rows
vlarray[[1,3]] = new_1_and_3_rows
"""
self._g_check_open()
self._v_file._check_writable()
if is_idx(key):
# If key is not a sequence, convert to it
coords = [key]
value = [value]
elif isinstance(key, slice):
start, stop, step = self._process_range(
key.start, key.stop, key.step)
coords = range(start, stop, step)
# Try with a boolean or point selection
elif type(key) in (list, tuple) or isinstance(key, np.ndarray):
coords = self._point_selection(key)
else:
raise IndexError(f"Invalid index or slice: {key!r}")
# Do the assignment row by row
self._assign_values(coords, value)
# Accessor for the _read_array method in superclass
def read(self, start=None, stop=None, step=1):
"""Get data in the array as a list of objects of the current flavor.
Please note that, as the lengths of the different rows are variable,
the returned value is a *Python list* (not an array of the current
flavor), with as many entries as specified rows in the range
parameters.
The start, stop and step parameters can be used to select only a
*range of rows* in the array. Their meanings are the same as in
the built-in range() Python function, except that negative values
of step are not allowed yet. Moreover, if only start is specified,
then stop will be set to start + 1. If you do not specify neither
start nor stop, then *all the rows* in the array are selected.
"""
self._g_check_open()
start, stop, step = self._process_range_read(start, stop, step)
if start == stop:
listarr = []
else:
listarr = self._read_array(start, stop, step)
atom = self.atom
if not hasattr(atom, 'size'): # it is a pseudo-atom
outlistarr = [atom.fromarray(arr) for arr in listarr]
else:
# Convert the list to the right flavor
flavor = self.flavor
outlistarr = [internal_to_flavor(arr, flavor) for arr in listarr]
return outlistarr
def _read_coordinates(self, coords):
"""Read rows specified in `coords`."""
rows = []
for coord in coords:
rows.append(self.read(idx2long(coord), idx2long(coord) + 1, 1)[0])
return rows
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."""
# Build the new VLArray object
object = VLArray(
group, name, self.atom, title=title, filters=filters,
expectedrows=self._v_expectedrows, chunkshape=chunkshape,
_log=_log)
# Now, fill the new vlarray with values from the old one
# This is not buffered because we cannot forsee the length
# of each record. So, the safest would be a copy row by row.
# In the future, some analysis can be done in order to buffer
# the copy process.
nrowsinbuf = 1
(start, stop, step) = self._process_range_read(start, stop, step)
# Optimized version (no conversions, no type and shape checks, etc...)
nrowscopied = SizeType(0)
nbytes = 0
if not hasattr(self.atom, 'size'): # it is a pseudo-atom
atomsize = self.atom.base.size
else:
atomsize = self.atom.size
for start2 in range(start, stop, step * nrowsinbuf):
# Save the records on disk
stop2 = start2 + step * nrowsinbuf
if stop2 > stop:
stop2 = stop
nparr = self._read_array(start=start2, stop=stop2, step=step)[0]
nobjects = nparr.shape[0]
object._append(nparr, nobjects)
nbytes += nobjects * atomsize
nrowscopied += 1
object.nrows = nrowscopied
return (object, nbytes)
def __repr__(self):
"""This provides more metainfo in addition to standard __str__"""
return f"""{self}
atom = {self.atom!r}
byteorder = {self.byteorder!r}
nrows = {self.nrows}
flavor = {self.flavor!r}"""
| (parentnode, name, atom=None, title='', filters=None, expectedrows=None, chunkshape=None, byteorder=None, _log=True, track_times=True) |
729,164 | tables.vlarray | __getitem__ | Get a row or a range of rows from the array.
If key argument is an integer, the corresponding array row is returned
as an object of the current flavor. If key is a slice, the range of
rows determined by it is returned as a list of objects 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 array has.
Examples
--------
::
a_row = vlarray[4]
a_list = vlarray[4:1000:2]
a_list2 = vlarray[[0,2]] # get list of coords
a_list3 = vlarray[[0,-2]] # negative values accepted
a_list4 = vlarray[np.array([True,...,False])] # array of bools
| def __getitem__(self, key):
"""Get a row or a range of rows from the array.
If key argument is an integer, the corresponding array row is returned
as an object of the current flavor. If key is a slice, the range of
rows determined by it is returned as a list of objects 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 array has.
Examples
--------
::
a_row = vlarray[4]
a_list = vlarray[4:1000:2]
a_list2 = vlarray[[0,2]] # get list of coords
a_list3 = vlarray[[0,-2]] # negative values accepted
a_list4 = vlarray[np.array([True,...,False])] # array of bools
"""
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):
coords = self._point_selection(key)
return self._read_coordinates(coords)
else:
raise IndexError(f"Invalid index or slice: {key!r}")
| (self, key) |
729,165 | tables.vlarray | __init__ | null | def __init__(self, parentnode, name, atom=None, title="",
filters=None, expectedrows=None,
chunkshape=None, byteorder=None,
_log=True, track_times=True):
self._v_version = None
"""The object version of this array."""
self._v_new = new = atom 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 array."""
if expectedrows is None:
expectedrows = parentnode._v_file.params['EXPECTED_ROWS_VLARRAY']
self._v_expectedrows = expectedrows
"""The expected number of rows to be stored in the array.
.. versionadded:: 3.0
"""
self._v_chunkshape = None
"""Private storage for the `chunkshape` property of Leaf."""
# Miscellaneous iteration rubbish.
self._start = None
"""Starting row for the current iteration."""
self._stop = None
"""Stopping row for the current iteration."""
self._step = None
"""Step size for the current iteration."""
self._nrowsread = None
"""Number of rows read up to the current state of iteration."""
self._startb = None
"""Starting row for current buffer."""
self._stopb = None
"""Stopping row for current buffer. """
self._row = None
"""Current row in iterators (sentinel)."""
self._init = False
"""Whether we are in the middle of an iteration or not (sentinel)."""
self.listarr = None
"""Current buffer in iterators."""
# Documented (*public*) attributes.
self.atom = atom
"""
An Atom (see :ref:`AtomClassDescr`) instance representing the
*type* and *shape* of the atomic objects to be saved. You may
use a *pseudo-atom* for storing a serialized object or
variable length string per row.
"""
self.nrow = None
"""On iterators, this is the index of the current row."""
self.nrows = None
"""The current number of rows in the array."""
self.extdim = 0 # VLArray only have one dimension currently
"""The index of the enlargeable dimension (always 0 for vlarrays)."""
# 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, atom=None, title='', filters=None, expectedrows=None, chunkshape=None, byteorder=None, _log=True, track_times=True) |
729,166 | tables.vlarray | __iter__ | Iterate over the rows of the array.
This is equivalent to calling :meth:`VLArray.iterrows` with default
arguments, i.e. it iterates over *all the rows* in the array.
Examples
--------
::
result = [row for row in vlarray]
Which is equivalent to::
result = [row for row in vlarray.iterrows()]
| def __iter__(self):
"""Iterate over the rows of the array.
This is equivalent to calling :meth:`VLArray.iterrows` with default
arguments, i.e. it iterates over *all the rows* in the array.
Examples
--------
::
result = [row for row in vlarray]
Which is equivalent to::
result = [row for row in vlarray.iterrows()]
"""
if not self._init:
# If the iterator is called directly, assign default variables
self._start = 0
self._stop = self.nrows
self._step = 1
# and initialize the loop
self._init_loop()
return self
| (self) |
729,168 | tables.vlarray | __next__ | Get the next element of the array during an iteration.
The element is returned as a list of objects of the current
flavor.
| def __next__(self):
"""Get the next element of the array during an iteration.
The element is returned as a list of objects of the current
flavor.
"""
if self._nrowsread >= self._stop:
self._init = False
raise StopIteration # end of iteration
else:
# Read a chunk of rows
if self._row + 1 >= self.nrowsinbuf or self._row < 0:
self._stopb = self._startb + self._step * self.nrowsinbuf
self.listarr = self.read(self._startb, self._stopb, self._step)
self._row = -1
self._startb = self._stopb
self._row += 1
self.nrow += self._step
self._nrowsread += self._step
return self.listarr[self._row]
| (self) |
729,169 | tables.vlarray | __repr__ | This provides more metainfo in addition to standard __str__ | """Here is defined the VLArray class."""
import operator
import sys
import numpy as np
from . import hdf5extension
from .atom import ObjectAtom, VLStringAtom, VLUnicodeAtom
from .flavor import internal_to_flavor
from .leaf import Leaf, calc_chunksize
from .utils import (
convert_to_np_atom, convert_to_np_atom2, idx2long, correct_byteorder,
SizeType, is_idx, lazyattr)
# default version for VLARRAY objects
# obversion = "1.0" # initial version
# obversion = "1.0" # add support for complex datatypes
# obversion = "1.1" # This adds support for time datatypes.
# obversion = "1.2" # This adds support for enumerated datatypes.
# obversion = "1.3" # Introduced 'PSEUDOATOM' attribute.
obversion = "1.4" # Numeric and numarray flavors are gone.
class VLArray(hdf5extension.VLArray, Leaf):
"""This class represents variable length (ragged) arrays in an HDF5 file.
Instances of this class represent array objects in the object tree
with the property that their rows can have a *variable* number of
homogeneous elements, called *atoms*. Like Table datasets (see
:ref:`TableClassDescr`), variable length arrays can have only one
dimension, and the elements (atoms) of their rows can be fully
multidimensional.
When reading a range of rows from a VLArray, you will *always* get
a Python list of objects of the current flavor (each of them for a
row), which may have different lengths.
This class provides methods to write or read data to or from
variable length array objects in the file. Note that it also
inherits all the public attributes and methods that Leaf (see
:ref:`LeafClassDescr`) already provides.
.. note::
VLArray objects also support compression although compression
is only performed on the data structures used internally by
the HDF5 to take references of the location of the variable
length data. Data itself (the raw data) are not compressed
or filtered.
Please refer to the `VLTypes Technical Note
<https://support.hdfgroup.org/HDF5/doc/TechNotes/VLTypes.html>`_
for more details on the topic.
Parameters
----------
parentnode
The parent :class:`Group` object.
name : str
The name of this node in its parent group.
atom
An `Atom` instance representing the *type* and *shape* of the atomic
objects to be saved.
title
A description for this node (it sets the ``TITLE`` HDF5 attribute on
disk).
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 row elements that will
be added to the growable dimension in the `VLArray` node.
If not provided, the default value is ``EXPECTED_ROWS_VLARRAY``
(see ``tables/parameters.py``). If you plan to create either
a much smaller or a much bigger `VLArray` try providing a guess;
this will optimize the HDF5 B-Tree creation and management
process time and the amount of memory used.
.. versionadded:: 3.0
chunkshape
The shape of the data chunk to be read or written in a single HDF5 I/O
operation. Filters are applied to those chunks of data. The
dimensionality of `chunkshape` must be 1. If ``None``, a sensible
value is calculated (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.
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
.. versionchanged:: 3.0
*parentNode* renamed into *parentnode*.
.. versionchanged:: 3.0
The *expectedsizeinMB* parameter has been replaced by *expectedrows*.
Examples
--------
See below a small example of the use of the VLArray class. The code is
available in :file:`examples/vlarray1.py`::
import numpy as np
import tables as tb
# Create a VLArray:
fileh = tb.open_file('vlarray1.h5', mode='w')
vlarray = fileh.create_vlarray(
fileh.root,
'vlarray1',
tb.Int32Atom(shape=()),
"ragged array of ints",
filters=tb.Filters(1))
# Append some (variable length) rows:
vlarray.append(np.array([5, 6]))
vlarray.append(np.array([5, 6, 7]))
vlarray.append([5, 6, 9, 8])
# Now, read it through an iterator:
print('-->', vlarray.title)
for x in vlarray:
print('%s[%d]--> %s' % (vlarray.name, vlarray.nrow, x))
# Now, do the same with native Python strings.
vlarray2 = fileh.create_vlarray(
fileh.root,
'vlarray2',
tb.StringAtom(itemsize=2),
"ragged array of strings",
filters=tb.Filters(1))
vlarray2.flavor = 'python'
# Append some (variable length) rows:
print('-->', vlarray2.title)
vlarray2.append(['5', '66'])
vlarray2.append(['5', '6', '77'])
vlarray2.append(['5', '6', '9', '88'])
# Now, read it through an iterator:
for x in vlarray2:
print('%s[%d]--> %s' % (vlarray2.name, vlarray2.nrow, x))
# Close the file.
fileh.close()
The output for the previous script is something like::
--> ragged array of ints
vlarray1[0]--> [5 6]
vlarray1[1]--> [5 6 7]
vlarray1[2]--> [5 6 9 8]
--> ragged array of strings
vlarray2[0]--> ['5', '66']
vlarray2[1]--> ['5', '6', '77']
vlarray2[2]--> ['5', '6', '9', '88']
.. rubric:: VLArray attributes
The instance variables below are provided in addition to those in
Leaf (see :ref:`LeafClassDescr`).
.. attribute:: atom
An Atom (see :ref:`AtomClassDescr`)
instance representing the *type* and
*shape* of the atomic objects to be
saved. You may use a *pseudo-atom* for
storing a serialized object or variable length string per row.
.. attribute:: flavor
The type of data object read from this leaf.
Please note that when reading several rows of VLArray data,
the flavor only applies to the *components* of the returned
Python list, not to the list itself.
.. attribute:: nrow
On iterators, this is the index of the current row.
.. attribute:: nrows
The current number of rows in the array.
.. attribute:: extdim
The index of the enlargeable dimension (always 0 for vlarrays).
"""
# Class identifier.
_c_classid = 'VLARRAY'
@lazyattr
def dtype(self):
"""The NumPy ``dtype`` that most closely matches this array."""
return self.atom.dtype
@property
def shape(self):
"""The shape of the stored array."""
return (self.nrows,)
@property
def size_on_disk(self):
"""
The HDF5 library does not include a function to determine size_on_disk
for variable-length arrays. Accessing this attribute will raise a
NotImplementedError.
"""
raise NotImplementedError('size_on_disk not implemented for VLArrays')
@property
def size_in_memory(self):
"""
The size of this array's data in bytes when it is fully loaded
into memory.
.. note::
When data is stored in a VLArray using the ObjectAtom type,
it is first serialized using pickle, and then converted to
a NumPy array suitable for storage in an HDF5 file.
This attribute will return the size of that NumPy
representation. If you wish to know the size of the Python
objects after they are loaded from disk, you can use this
`ActiveState recipe
<http://code.activestate.com/recipes/577504/>`_.
"""
return self._get_memory_size()
def __init__(self, parentnode, name, atom=None, title="",
filters=None, expectedrows=None,
chunkshape=None, byteorder=None,
_log=True, track_times=True):
self._v_version = None
"""The object version of this array."""
self._v_new = new = atom 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 array."""
if expectedrows is None:
expectedrows = parentnode._v_file.params['EXPECTED_ROWS_VLARRAY']
self._v_expectedrows = expectedrows
"""The expected number of rows to be stored in the array.
.. versionadded:: 3.0
"""
self._v_chunkshape = None
"""Private storage for the `chunkshape` property of Leaf."""
# Miscellaneous iteration rubbish.
self._start = None
"""Starting row for the current iteration."""
self._stop = None
"""Stopping row for the current iteration."""
self._step = None
"""Step size for the current iteration."""
self._nrowsread = None
"""Number of rows read up to the current state of iteration."""
self._startb = None
"""Starting row for current buffer."""
self._stopb = None
"""Stopping row for current buffer. """
self._row = None
"""Current row in iterators (sentinel)."""
self._init = False
"""Whether we are in the middle of an iteration or not (sentinel)."""
self.listarr = None
"""Current buffer in iterators."""
# Documented (*public*) attributes.
self.atom = atom
"""
An Atom (see :ref:`AtomClassDescr`) instance representing the
*type* and *shape* of the atomic objects to be saved. You may
use a *pseudo-atom* for storing a serialized object or
variable length string per row.
"""
self.nrow = None
"""On iterators, this is the index of the current row."""
self.nrows = None
"""The current number of rows in the array."""
self.extdim = 0 # VLArray only have one dimension currently
"""The index of the enlargeable dimension (always 0 for vlarrays)."""
# 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):
super()._g_post_init_hook()
self.nrowsinbuf = 100 # maybe enough for most applications
# This is too specific for moving it into Leaf
def _calc_chunkshape(self, expectedrows):
"""Calculate the size for the HDF5 chunk."""
# For computing the chunkshape for HDF5 VL types, we have to
# choose the itemsize of the *each* element of the atom and
# not the size of the entire atom. I don't know why this
# should be like this, perhaps I should report this to the
# HDF5 list.
# F. Alted 2006-11-23
# elemsize = self.atom.atomsize()
elemsize = self._basesize
# AV 2013-05-03
# This is just a quick workaround tha allows to change the API for
# PyTables 3.0 release and remove the expected_mb parameter.
# The algorithm for computing the chunkshape should be rewritten as
# requested by gh-35.
expected_mb = expectedrows * elemsize / 1024 ** 2
chunksize = calc_chunksize(expected_mb)
# Set the chunkshape
chunkshape = chunksize // elemsize
# Safeguard against itemsizes being extremely large
if chunkshape == 0:
chunkshape = 1
return (SizeType(chunkshape),)
def _g_create(self):
"""Create a variable length array (ragged array)."""
atom = self.atom
self._v_version = obversion
# Check for zero dims in atom shape (not allowed in VLArrays)
zerodims = np.sum(np.array(atom.shape) == 0)
if zerodims > 0:
raise ValueError("When creating VLArrays, none of the dimensions "
"of the Atom instance can be zero.")
if not hasattr(atom, 'size'): # it is a pseudo-atom
self._atomicdtype = atom.base.dtype
self._atomicsize = atom.base.size
self._basesize = atom.base.itemsize
else:
self._atomicdtype = atom.dtype
self._atomicsize = atom.size
self._basesize = atom.itemsize
self._atomictype = atom.type
self._atomicshape = atom.shape
# Compute the optimal chunkshape, if needed
if self._v_chunkshape is None:
self._v_chunkshape = self._calc_chunkshape(self._v_expectedrows)
self.nrows = SizeType(0) # No rows at creation time
# Correct the byteorder if needed
if self.byteorder is None:
self.byteorder = correct_byteorder(atom.type, sys.byteorder)
# After creating the vlarray, ``self._v_objectid`` needs to be
# set because it is needed for setting attributes afterwards.
self._v_objectid = self._create_array(self._v_new_title)
# Add an attribute in case we have a pseudo-atom so that we
# can retrieve the proper class after a re-opening operation.
if not hasattr(atom, 'size'): # it is a pseudo-atom
self.attrs.PSEUDOATOM = atom.kind
return self._v_objectid
def _g_open(self):
"""Get the metadata info for an array in file."""
self._v_objectid, self.nrows, self._v_chunkshape, atom = \
self._open_array()
# Check if the atom can be a PseudoAtom
if "PSEUDOATOM" in self.attrs:
kind = self.attrs.PSEUDOATOM
if kind == 'vlstring':
atom = VLStringAtom()
elif kind == 'vlunicode':
atom = VLUnicodeAtom()
elif kind == 'object':
atom = ObjectAtom()
else:
raise ValueError(
"pseudo-atom name ``%s`` not known." % kind)
elif self._v_file.format_version[:1] == "1":
flavor1x = self.attrs.FLAVOR
if flavor1x == "VLString":
atom = VLStringAtom()
elif flavor1x == "Object":
atom = ObjectAtom()
self.atom = atom
return self._v_objectid
def _getnobjects(self, nparr):
"""Return the number of objects in a NumPy array."""
# Check for zero dimensionality array
zerodims = np.sum(np.array(nparr.shape) == 0)
if zerodims > 0:
# No objects to be added
return 0
shape = nparr.shape
atom_shape = self.atom.shape
shapelen = len(nparr.shape)
if isinstance(atom_shape, tuple):
atomshapelen = len(self.atom.shape)
else:
atom_shape = (self.atom.shape,)
atomshapelen = 1
diflen = shapelen - atomshapelen
if shape == atom_shape:
nobjects = 1
elif (diflen == 1 and shape[diflen:] == atom_shape):
# Check if the leading dimensions are all ones
# if shape[:diflen-1] == (1,)*(diflen-1):
# nobjects = shape[diflen-1]
# shape = shape[diflen:]
# It's better to accept only inputs with the exact dimensionality
# i.e. a dimensionality only 1 element larger than atom
nobjects = shape[0]
shape = shape[1:]
elif atom_shape == (1,) and shapelen == 1:
# Case where shape = (N,) and shape_atom = 1 or (1,)
nobjects = shape[0]
else:
raise ValueError("The object '%s' is composed of elements with "
"shape '%s', which is not compatible with the "
"atom shape ('%s')." % (nparr, shape, atom_shape))
return nobjects
def get_enum(self):
"""Get the enumerated type associated with this array.
If this array 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 self.atom.kind != 'enum':
raise TypeError("array ``%s`` is not of an enumerated type"
% self._v_pathname)
return self.atom.enum
def append(self, sequence):
"""Add a sequence of data to the end of the dataset.
This method appends the objects in the sequence to a *single row* in
this array. The type and shape of individual objects must be compliant
with the atoms in the array. In the case of serialized objects and
variable length strings, the object or string to append is itself the
sequence.
"""
self._g_check_open()
self._v_file._check_writable()
# Prepare the sequence to convert it into a NumPy object
atom = self.atom
if not hasattr(atom, 'size'): # it is a pseudo-atom
sequence = atom.toarray(sequence)
statom = atom.base
else:
try: # fastest check in most cases
len(sequence)
except TypeError:
raise TypeError("argument is not a sequence")
statom = atom
if len(sequence) > 0:
# The sequence needs to be copied to make the operation safe
# to in-place conversion.
nparr = convert_to_np_atom2(sequence, statom)
nobjects = self._getnobjects(nparr)
else:
nobjects = 0
nparr = None
self._append(nparr, nobjects)
self.nrows += 1
def iterrows(self, start=None, stop=None, step=None):
"""Iterate over the rows of the array.
This method returns an iterator yielding an object of the current
flavor for each selected row in the array.
If a range is not supplied, *all the rows* in the array are iterated
upon. You can also use the :meth:`VLArray.__iter__` special method for
that purpose. If you only want to iterate over a given *range of rows*
in the array, you may use the start, stop and step parameters.
Examples
--------
::
for row in vlarray.iterrows(step=4):
print('%s[%d]--> %s' % (vlarray.name, vlarray.nrow, row))
.. versionchanged:: 3.0
If the *start* parameter is provided and *stop* is None then the
array is iterated from *start* to the last line.
In PyTables < 3.0 only one element was returned.
"""
(self._start, self._stop, self._step) = self._process_range(
start, stop, step)
self._init_loop()
return self
def __iter__(self):
"""Iterate over the rows of the array.
This is equivalent to calling :meth:`VLArray.iterrows` with default
arguments, i.e. it iterates over *all the rows* in the array.
Examples
--------
::
result = [row for row in vlarray]
Which is equivalent to::
result = [row for row in vlarray.iterrows()]
"""
if not self._init:
# If the iterator is called directly, assign default variables
self._start = 0
self._stop = self.nrows
self._step = 1
# and initialize the loop
self._init_loop()
return self
def _init_loop(self):
"""Initialization for the __iter__ iterator."""
self._nrowsread = self._start
self._startb = self._start
self._row = -1 # Sentinel
self._init = True # Sentinel
self.nrow = SizeType(self._start - self._step) # row number
def __next__(self):
"""Get the next element of the array during an iteration.
The element is returned as a list of objects of the current
flavor.
"""
if self._nrowsread >= self._stop:
self._init = False
raise StopIteration # end of iteration
else:
# Read a chunk of rows
if self._row + 1 >= self.nrowsinbuf or self._row < 0:
self._stopb = self._startb + self._step * self.nrowsinbuf
self.listarr = self.read(self._startb, self._stopb, self._step)
self._row = -1
self._startb = self._stopb
self._row += 1
self.nrow += self._step
self._nrowsread += self._step
return self.listarr[self._row]
def __getitem__(self, key):
"""Get a row or a range of rows from the array.
If key argument is an integer, the corresponding array row is returned
as an object of the current flavor. If key is a slice, the range of
rows determined by it is returned as a list of objects 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 array has.
Examples
--------
::
a_row = vlarray[4]
a_list = vlarray[4:1000:2]
a_list2 = vlarray[[0,2]] # get list of coords
a_list3 = vlarray[[0,-2]] # negative values accepted
a_list4 = vlarray[np.array([True,...,False])] # array of bools
"""
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):
coords = self._point_selection(key)
return self._read_coordinates(coords)
else:
raise IndexError(f"Invalid index or slice: {key!r}")
def _assign_values(self, coords, values):
"""Assign the `values` to the positions stated in `coords`."""
for nrow, value in zip(coords, values):
if nrow >= self.nrows:
raise IndexError("First index out of range")
if nrow < 0:
# To support negative values
nrow += self.nrows
object_ = value
# Prepare the object to convert it into a NumPy object
atom = self.atom
if not hasattr(atom, 'size'): # it is a pseudo-atom
object_ = atom.toarray(object_)
statom = atom.base
else:
statom = atom
value = convert_to_np_atom(object_, statom)
nobjects = self._getnobjects(value)
# Get the previous value
nrow = idx2long(
nrow) # To convert any possible numpy scalar value
nparr = self._read_array(nrow, nrow + 1, 1)[0]
nobjects = len(nparr)
if len(value) > nobjects:
raise ValueError("Length of value (%s) is larger than number "
"of elements in row (%s)" % (len(value),
nobjects))
try:
nparr[:] = value
except Exception as exc: # XXX
raise ValueError("Value parameter:\n'%r'\n"
"cannot be converted into an array object "
"compliant vlarray[%s] row: \n'%r'\n"
"The error was: <%s>" % (value, nrow,
nparr[:], exc))
if nparr.size > 0:
self._modify(nrow, nparr, nobjects)
def __setitem__(self, key, value):
"""Set a row, or set of rows, in the array.
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
of rows 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.
.. note::
When updating the rows of a VLArray object which uses a
pseudo-atom, there is a problem: you can only update values
with *exactly* the same size in bytes than the original row.
This is very difficult to meet with object pseudo-atoms,
because :mod:`pickle` applied on a Python object does not
guarantee to return the same number of bytes than over another
object, even if they are of the same class.
This effectively limits the kinds of objects than can be
updated in variable-length arrays.
Examples
--------
::
vlarray[0] = vlarray[0] * 2 + 3
vlarray[99] = arange(96) * 2 + 3
# Negative values for the index are supported.
vlarray[-99] = vlarray[5] * 2 + 3
vlarray[1:30:2] = list_of_rows
vlarray[[1,3]] = new_1_and_3_rows
"""
self._g_check_open()
self._v_file._check_writable()
if is_idx(key):
# If key is not a sequence, convert to it
coords = [key]
value = [value]
elif isinstance(key, slice):
start, stop, step = self._process_range(
key.start, key.stop, key.step)
coords = range(start, stop, step)
# Try with a boolean or point selection
elif type(key) in (list, tuple) or isinstance(key, np.ndarray):
coords = self._point_selection(key)
else:
raise IndexError(f"Invalid index or slice: {key!r}")
# Do the assignment row by row
self._assign_values(coords, value)
# Accessor for the _read_array method in superclass
def read(self, start=None, stop=None, step=1):
"""Get data in the array as a list of objects of the current flavor.
Please note that, as the lengths of the different rows are variable,
the returned value is a *Python list* (not an array of the current
flavor), with as many entries as specified rows in the range
parameters.
The start, stop and step parameters can be used to select only a
*range of rows* in the array. Their meanings are the same as in
the built-in range() Python function, except that negative values
of step are not allowed yet. Moreover, if only start is specified,
then stop will be set to start + 1. If you do not specify neither
start nor stop, then *all the rows* in the array are selected.
"""
self._g_check_open()
start, stop, step = self._process_range_read(start, stop, step)
if start == stop:
listarr = []
else:
listarr = self._read_array(start, stop, step)
atom = self.atom
if not hasattr(atom, 'size'): # it is a pseudo-atom
outlistarr = [atom.fromarray(arr) for arr in listarr]
else:
# Convert the list to the right flavor
flavor = self.flavor
outlistarr = [internal_to_flavor(arr, flavor) for arr in listarr]
return outlistarr
def _read_coordinates(self, coords):
"""Read rows specified in `coords`."""
rows = []
for coord in coords:
rows.append(self.read(idx2long(coord), idx2long(coord) + 1, 1)[0])
return rows
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."""
# Build the new VLArray object
object = VLArray(
group, name, self.atom, title=title, filters=filters,
expectedrows=self._v_expectedrows, chunkshape=chunkshape,
_log=_log)
# Now, fill the new vlarray with values from the old one
# This is not buffered because we cannot forsee the length
# of each record. So, the safest would be a copy row by row.
# In the future, some analysis can be done in order to buffer
# the copy process.
nrowsinbuf = 1
(start, stop, step) = self._process_range_read(start, stop, step)
# Optimized version (no conversions, no type and shape checks, etc...)
nrowscopied = SizeType(0)
nbytes = 0
if not hasattr(self.atom, 'size'): # it is a pseudo-atom
atomsize = self.atom.base.size
else:
atomsize = self.atom.size
for start2 in range(start, stop, step * nrowsinbuf):
# Save the records on disk
stop2 = start2 + step * nrowsinbuf
if stop2 > stop:
stop2 = stop
nparr = self._read_array(start=start2, stop=stop2, step=step)[0]
nobjects = nparr.shape[0]
object._append(nparr, nobjects)
nbytes += nobjects * atomsize
nrowscopied += 1
object.nrows = nrowscopied
return (object, nbytes)
def __repr__(self):
"""This provides more metainfo in addition to standard __str__"""
return f"""{self}
atom = {self.atom!r}
byteorder = {self.byteorder!r}
nrows = {self.nrows}
flavor = {self.flavor!r}"""
| (self) |
729,170 | tables.vlarray | __setitem__ | Set a row, or set of rows, in the array.
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
of rows 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.
.. note::
When updating the rows of a VLArray object which uses a
pseudo-atom, there is a problem: you can only update values
with *exactly* the same size in bytes than the original row.
This is very difficult to meet with object pseudo-atoms,
because :mod:`pickle` applied on a Python object does not
guarantee to return the same number of bytes than over another
object, even if they are of the same class.
This effectively limits the kinds of objects than can be
updated in variable-length arrays.
Examples
--------
::
vlarray[0] = vlarray[0] * 2 + 3
vlarray[99] = arange(96) * 2 + 3
# Negative values for the index are supported.
vlarray[-99] = vlarray[5] * 2 + 3
vlarray[1:30:2] = list_of_rows
vlarray[[1,3]] = new_1_and_3_rows
| def __setitem__(self, key, value):
"""Set a row, or set of rows, in the array.
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
of rows 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.
.. note::
When updating the rows of a VLArray object which uses a
pseudo-atom, there is a problem: you can only update values
with *exactly* the same size in bytes than the original row.
This is very difficult to meet with object pseudo-atoms,
because :mod:`pickle` applied on a Python object does not
guarantee to return the same number of bytes than over another
object, even if they are of the same class.
This effectively limits the kinds of objects than can be
updated in variable-length arrays.
Examples
--------
::
vlarray[0] = vlarray[0] * 2 + 3
vlarray[99] = arange(96) * 2 + 3
# Negative values for the index are supported.
vlarray[-99] = vlarray[5] * 2 + 3
vlarray[1:30:2] = list_of_rows
vlarray[[1,3]] = new_1_and_3_rows
"""
self._g_check_open()
self._v_file._check_writable()
if is_idx(key):
# If key is not a sequence, convert to it
coords = [key]
value = [value]
elif isinstance(key, slice):
start, stop, step = self._process_range(
key.start, key.stop, key.step)
coords = range(start, stop, step)
# Try with a boolean or point selection
elif type(key) in (list, tuple) or isinstance(key, np.ndarray):
coords = self._point_selection(key)
else:
raise IndexError(f"Invalid index or slice: {key!r}")
# Do the assignment row by row
self._assign_values(coords, value)
| (self, key, value) |
729,172 | tables.vlarray | _assign_values | Assign the `values` to the positions stated in `coords`. | def _assign_values(self, coords, values):
"""Assign the `values` to the positions stated in `coords`."""
for nrow, value in zip(coords, values):
if nrow >= self.nrows:
raise IndexError("First index out of range")
if nrow < 0:
# To support negative values
nrow += self.nrows
object_ = value
# Prepare the object to convert it into a NumPy object
atom = self.atom
if not hasattr(atom, 'size'): # it is a pseudo-atom
object_ = atom.toarray(object_)
statom = atom.base
else:
statom = atom
value = convert_to_np_atom(object_, statom)
nobjects = self._getnobjects(value)
# Get the previous value
nrow = idx2long(
nrow) # To convert any possible numpy scalar value
nparr = self._read_array(nrow, nrow + 1, 1)[0]
nobjects = len(nparr)
if len(value) > nobjects:
raise ValueError("Length of value (%s) is larger than number "
"of elements in row (%s)" % (len(value),
nobjects))
try:
nparr[:] = value
except Exception as exc: # XXX
raise ValueError("Value parameter:\n'%r'\n"
"cannot be converted into an array object "
"compliant vlarray[%s] row: \n'%r'\n"
"The error was: <%s>" % (value, nrow,
nparr[:], exc))
if nparr.size > 0:
self._modify(nrow, nparr, nobjects)
| (self, coords, values) |
729,173 | tables.vlarray | _calc_chunkshape | Calculate the size for the HDF5 chunk. | def _calc_chunkshape(self, expectedrows):
"""Calculate the size for the HDF5 chunk."""
# For computing the chunkshape for HDF5 VL types, we have to
# choose the itemsize of the *each* element of the atom and
# not the size of the entire atom. I don't know why this
# should be like this, perhaps I should report this to the
# HDF5 list.
# F. Alted 2006-11-23
# elemsize = self.atom.atomsize()
elemsize = self._basesize
# AV 2013-05-03
# This is just a quick workaround tha allows to change the API for
# PyTables 3.0 release and remove the expected_mb parameter.
# The algorithm for computing the chunkshape should be rewritten as
# requested by gh-35.
expected_mb = expectedrows * elemsize / 1024 ** 2
chunksize = calc_chunksize(expected_mb)
# Set the chunkshape
chunkshape = chunksize // elemsize
# Safeguard against itemsizes being extremely large
if chunkshape == 0:
chunkshape = 1
return (SizeType(chunkshape),)
| (self, expectedrows) |
729,190 | tables.vlarray | _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."""
# Build the new VLArray object
object = VLArray(
group, name, self.atom, title=title, filters=filters,
expectedrows=self._v_expectedrows, chunkshape=chunkshape,
_log=_log)
# Now, fill the new vlarray with values from the old one
# This is not buffered because we cannot forsee the length
# of each record. So, the safest would be a copy row by row.
# In the future, some analysis can be done in order to buffer
# the copy process.
nrowsinbuf = 1
(start, stop, step) = self._process_range_read(start, stop, step)
# Optimized version (no conversions, no type and shape checks, etc...)
nrowscopied = SizeType(0)
nbytes = 0
if not hasattr(self.atom, 'size'): # it is a pseudo-atom
atomsize = self.atom.base.size
else:
atomsize = self.atom.size
for start2 in range(start, stop, step * nrowsinbuf):
# Save the records on disk
stop2 = start2 + step * nrowsinbuf
if stop2 > stop:
stop2 = stop
nparr = self._read_array(start=start2, stop=stop2, step=step)[0]
nobjects = nparr.shape[0]
object._append(nparr, nobjects)
nbytes += nobjects * atomsize
nrowscopied += 1
object.nrows = nrowscopied
return (object, nbytes)
| (self, group, name, start, stop, step, title, filters, chunkshape, _log, **kwargs) |
729,191 | tables.vlarray | _g_create | Create a variable length array (ragged array). | def _g_create(self):
"""Create a variable length array (ragged array)."""
atom = self.atom
self._v_version = obversion
# Check for zero dims in atom shape (not allowed in VLArrays)
zerodims = np.sum(np.array(atom.shape) == 0)
if zerodims > 0:
raise ValueError("When creating VLArrays, none of the dimensions "
"of the Atom instance can be zero.")
if not hasattr(atom, 'size'): # it is a pseudo-atom
self._atomicdtype = atom.base.dtype
self._atomicsize = atom.base.size
self._basesize = atom.base.itemsize
else:
self._atomicdtype = atom.dtype
self._atomicsize = atom.size
self._basesize = atom.itemsize
self._atomictype = atom.type
self._atomicshape = atom.shape
# Compute the optimal chunkshape, if needed
if self._v_chunkshape is None:
self._v_chunkshape = self._calc_chunkshape(self._v_expectedrows)
self.nrows = SizeType(0) # No rows at creation time
# Correct the byteorder if needed
if self.byteorder is None:
self.byteorder = correct_byteorder(atom.type, sys.byteorder)
# After creating the vlarray, ``self._v_objectid`` needs to be
# set because it is needed for setting attributes afterwards.
self._v_objectid = self._create_array(self._v_new_title)
# Add an attribute in case we have a pseudo-atom so that we
# can retrieve the proper class after a re-opening operation.
if not hasattr(atom, 'size'): # it is a pseudo-atom
self.attrs.PSEUDOATOM = atom.kind
return self._v_objectid
| (self) |
729,200 | tables.vlarray | _g_open | Get the metadata info for an array in file. | def _g_open(self):
"""Get the metadata info for an array in file."""
self._v_objectid, self.nrows, self._v_chunkshape, atom = \
self._open_array()
# Check if the atom can be a PseudoAtom
if "PSEUDOATOM" in self.attrs:
kind = self.attrs.PSEUDOATOM
if kind == 'vlstring':
atom = VLStringAtom()
elif kind == 'vlunicode':
atom = VLUnicodeAtom()
elif kind == 'object':
atom = ObjectAtom()
else:
raise ValueError(
"pseudo-atom name ``%s`` not known." % kind)
elif self._v_file.format_version[:1] == "1":
flavor1x = self.attrs.FLAVOR
if flavor1x == "VLString":
atom = VLStringAtom()
elif flavor1x == "Object":
atom = ObjectAtom()
self.atom = atom
return self._v_objectid
| (self) |
729,201 | tables.vlarray | _g_post_init_hook | null | def _g_post_init_hook(self):
super()._g_post_init_hook()
self.nrowsinbuf = 100 # maybe enough for most applications
| (self) |
729,209 | tables.vlarray | _getnobjects | Return the number of objects in a NumPy array. | def _getnobjects(self, nparr):
"""Return the number of objects in a NumPy array."""
# Check for zero dimensionality array
zerodims = np.sum(np.array(nparr.shape) == 0)
if zerodims > 0:
# No objects to be added
return 0
shape = nparr.shape
atom_shape = self.atom.shape
shapelen = len(nparr.shape)
if isinstance(atom_shape, tuple):
atomshapelen = len(self.atom.shape)
else:
atom_shape = (self.atom.shape,)
atomshapelen = 1
diflen = shapelen - atomshapelen
if shape == atom_shape:
nobjects = 1
elif (diflen == 1 and shape[diflen:] == atom_shape):
# Check if the leading dimensions are all ones
# if shape[:diflen-1] == (1,)*(diflen-1):
# nobjects = shape[diflen-1]
# shape = shape[diflen:]
# It's better to accept only inputs with the exact dimensionality
# i.e. a dimensionality only 1 element larger than atom
nobjects = shape[0]
shape = shape[1:]
elif atom_shape == (1,) and shapelen == 1:
# Case where shape = (N,) and shape_atom = 1 or (1,)
nobjects = shape[0]
else:
raise ValueError("The object '%s' is composed of elements with "
"shape '%s', which is not compatible with the "
"atom shape ('%s')." % (nparr, shape, atom_shape))
return nobjects
| (self, nparr) |
729,214 | tables.vlarray | _read_coordinates | Read rows specified in `coords`. | def _read_coordinates(self, coords):
"""Read rows specified in `coords`."""
rows = []
for coord in coords:
rows.append(self.read(idx2long(coord), idx2long(coord) + 1, 1)[0])
return rows
| (self, coords) |
729,215 | tables.vlarray | append | Add a sequence of data to the end of the dataset.
This method appends the objects in the sequence to a *single row* in
this array. The type and shape of individual objects must be compliant
with the atoms in the array. In the case of serialized objects and
variable length strings, the object or string to append is itself the
sequence.
| def append(self, sequence):
"""Add a sequence of data to the end of the dataset.
This method appends the objects in the sequence to a *single row* in
this array. The type and shape of individual objects must be compliant
with the atoms in the array. In the case of serialized objects and
variable length strings, the object or string to append is itself the
sequence.
"""
self._g_check_open()
self._v_file._check_writable()
# Prepare the sequence to convert it into a NumPy object
atom = self.atom
if not hasattr(atom, 'size'): # it is a pseudo-atom
sequence = atom.toarray(sequence)
statom = atom.base
else:
try: # fastest check in most cases
len(sequence)
except TypeError:
raise TypeError("argument is not a sequence")
statom = atom
if len(sequence) > 0:
# The sequence needs to be copied to make the operation safe
# to in-place conversion.
nparr = convert_to_np_atom2(sequence, statom)
nobjects = self._getnobjects(nparr)
else:
nobjects = 0
nparr = None
self._append(nparr, nobjects)
self.nrows += 1
| (self, sequence) |
729,223 | tables.vlarray | iterrows | Iterate over the rows of the array.
This method returns an iterator yielding an object of the current
flavor for each selected row in the array.
If a range is not supplied, *all the rows* in the array are iterated
upon. You can also use the :meth:`VLArray.__iter__` special method for
that purpose. If you only want to iterate over a given *range of rows*
in the array, you may use the start, stop and step parameters.
Examples
--------
::
for row in vlarray.iterrows(step=4):
print('%s[%d]--> %s' % (vlarray.name, vlarray.nrow, row))
.. versionchanged:: 3.0
If the *start* parameter is provided and *stop* is None then the
array is iterated from *start* to the last line.
In PyTables < 3.0 only one element was returned.
| def iterrows(self, start=None, stop=None, step=None):
"""Iterate over the rows of the array.
This method returns an iterator yielding an object of the current
flavor for each selected row in the array.
If a range is not supplied, *all the rows* in the array are iterated
upon. You can also use the :meth:`VLArray.__iter__` special method for
that purpose. If you only want to iterate over a given *range of rows*
in the array, you may use the start, stop and step parameters.
Examples
--------
::
for row in vlarray.iterrows(step=4):
print('%s[%d]--> %s' % (vlarray.name, vlarray.nrow, row))
.. versionchanged:: 3.0
If the *start* parameter is provided and *stop* is None then the
array is iterated from *start* to the last line.
In PyTables < 3.0 only one element was returned.
"""
(self._start, self._stop, self._step) = self._process_range(
start, stop, step)
self._init_loop()
return self
| (self, start=None, stop=None, step=None) |
729,225 | tables.vlarray | read | Get data in the array as a list of objects of the current flavor.
Please note that, as the lengths of the different rows are variable,
the returned value is a *Python list* (not an array of the current
flavor), with as many entries as specified rows in the range
parameters.
The start, stop and step parameters can be used to select only a
*range of rows* in the array. Their meanings are the same as in
the built-in range() Python function, except that negative values
of step are not allowed yet. Moreover, if only start is specified,
then stop will be set to start + 1. If you do not specify neither
start nor stop, then *all the rows* in the array are selected.
| def read(self, start=None, stop=None, step=1):
"""Get data in the array as a list of objects of the current flavor.
Please note that, as the lengths of the different rows are variable,
the returned value is a *Python list* (not an array of the current
flavor), with as many entries as specified rows in the range
parameters.
The start, stop and step parameters can be used to select only a
*range of rows* in the array. Their meanings are the same as in
the built-in range() Python function, except that negative values
of step are not allowed yet. Moreover, if only start is specified,
then stop will be set to start + 1. If you do not specify neither
start nor stop, then *all the rows* in the array are selected.
"""
self._g_check_open()
start, stop, step = self._process_range_read(start, stop, step)
if start == stop:
listarr = []
else:
listarr = self._read_array(start, stop, step)
atom = self.atom
if not hasattr(atom, 'size'): # it is a pseudo-atom
outlistarr = [atom.fromarray(arr) for arr in listarr]
else:
# Convert the list to the right flavor
flavor = self.flavor
outlistarr = [internal_to_flavor(arr, flavor) for arr in listarr]
return outlistarr
| (self, start=None, stop=None, step=1) |
729,230 | tables.atom | VLStringAtom | Defines an atom of type ``vlstring``.
This class describes a *row* of the VLArray class, rather than an atom. It
differs from the StringAtom class in that you can only add *one instance of
it to one specific row*, i.e. the :meth:`VLArray.append` method only
accepts one object when the base atom is of this type.
This class stores bytestrings. It does not make assumptions on the
encoding of the string, and raw bytes are stored as is. To store a string
you will need to *explicitly* convert it to a bytestring before you can
save them::
>>> s = 'A unicode string: hbar = ℏ'
>>> bytestring = s.encode('utf-8')
>>> VLArray.append(bytestring) # doctest: +SKIP
For full Unicode support, using VLUnicodeAtom (see :ref:`VLUnicodeAtom`) is
recommended.
Variable-length string atoms do not accept parameters and they cause the
reads of rows to always return Python bytestrings. You can regard vlstring
atoms as an easy way to save generic variable length strings.
| class VLStringAtom(_BufferedAtom):
"""Defines an atom of type ``vlstring``.
This class describes a *row* of the VLArray class, rather than an atom. It
differs from the StringAtom class in that you can only add *one instance of
it to one specific row*, i.e. the :meth:`VLArray.append` method only
accepts one object when the base atom is of this type.
This class stores bytestrings. It does not make assumptions on the
encoding of the string, and raw bytes are stored as is. To store a string
you will need to *explicitly* convert it to a bytestring before you can
save them::
>>> s = 'A unicode string: hbar = \u210f'
>>> bytestring = s.encode('utf-8')
>>> VLArray.append(bytestring) # doctest: +SKIP
For full Unicode support, using VLUnicodeAtom (see :ref:`VLUnicodeAtom`) is
recommended.
Variable-length string atoms do not accept parameters and they cause the
reads of rows to always return Python bytestrings. You can regard vlstring
atoms as an easy way to save generic variable length strings.
"""
kind = 'vlstring'
type = 'vlstring'
base = UInt8Atom()
def _tobuffer(self, object_):
if isinstance(object_, str):
warnings.warn("Storing non bytestrings in VLStringAtom is "
"deprecated.", DeprecationWarning)
elif not isinstance(object_, bytes):
raise TypeError(f"object is not a string: {object_!r}")
return np.bytes_(object_)
def fromarray(self, array):
return array.tobytes()
| () |
729,232 | tables.atom | _tobuffer | null | def _tobuffer(self, object_):
if isinstance(object_, str):
warnings.warn("Storing non bytestrings in VLStringAtom is "
"deprecated.", DeprecationWarning)
elif not isinstance(object_, bytes):
raise TypeError(f"object is not a string: {object_!r}")
return np.bytes_(object_)
| (self, object_) |
729,233 | tables.atom | fromarray | null | def fromarray(self, array):
return array.tobytes()
| (self, array) |
729,235 | tables.atom | VLUnicodeAtom | Defines an atom of type vlunicode.
This class describes a *row* of the VLArray class, rather than an atom. It
is very similar to VLStringAtom (see :ref:`VLStringAtom`), but it stores
Unicode strings (using 32-bit characters a la UCS-4, so all strings of the
same length also take up the same space).
This class does not make assumptions on the encoding of plain input
strings. Plain strings are supported as long as no character is out of the
ASCII set; otherwise, you will need to *explicitly* convert them to Unicode
before you can save them.
Variable-length Unicode atoms do not accept parameters and they cause the
reads of rows to always return Python Unicode strings. You can regard
vlunicode atoms as an easy way to save variable length Unicode strings.
| class VLUnicodeAtom(_BufferedAtom):
"""Defines an atom of type vlunicode.
This class describes a *row* of the VLArray class, rather than an atom. It
is very similar to VLStringAtom (see :ref:`VLStringAtom`), but it stores
Unicode strings (using 32-bit characters a la UCS-4, so all strings of the
same length also take up the same space).
This class does not make assumptions on the encoding of plain input
strings. Plain strings are supported as long as no character is out of the
ASCII set; otherwise, you will need to *explicitly* convert them to Unicode
before you can save them.
Variable-length Unicode atoms do not accept parameters and they cause the
reads of rows to always return Python Unicode strings. You can regard
vlunicode atoms as an easy way to save variable length Unicode strings.
"""
kind = 'vlunicode'
type = 'vlunicode'
base = UInt32Atom()
# numpy.unicode_ no more implements the buffer interface in Python 3
#
# When the Python build is UCS-2, we need to promote the
# Unicode string to UCS-4. We *must* use a 0-d array since
# NumPy scalars inherit the UCS-2 encoding from Python (see
# NumPy ticket #525). Since ``_tobuffer()`` can't return an
# array, we must override ``toarray()`` itself.
def toarray(self, object_):
if isinstance(object_, bytes):
warnings.warn("Storing bytestrings in VLUnicodeAtom is "
"deprecated.", DeprecationWarning)
elif not isinstance(object_, str):
raise TypeError(f"object is not a string: {object_!r}")
ustr = str(object_)
uarr = np.array(ustr, dtype='U')
return np.ndarray(
buffer=uarr, dtype=self.base.dtype, shape=len(ustr))
def _tobuffer(self, object_):
# This works (and is used) only with UCS-4 builds of Python,
# where the width of the internal representation of a
# character matches that of the base atoms.
if isinstance(object_, bytes):
warnings.warn("Storing bytestrings in VLUnicodeAtom is "
"deprecated.", DeprecationWarning)
elif not isinstance(object_, str):
raise TypeError(f"object is not a string: {object_!r}")
return np.str_(object_)
def fromarray(self, array):
length = len(array)
if length == 0:
return '' # ``array.view('U0')`` raises a `TypeError`
return array.view('U%d' % length).item()
| () |
729,237 | tables.atom | _tobuffer | null | def _tobuffer(self, object_):
# This works (and is used) only with UCS-4 builds of Python,
# where the width of the internal representation of a
# character matches that of the base atoms.
if isinstance(object_, bytes):
warnings.warn("Storing bytestrings in VLUnicodeAtom is "
"deprecated.", DeprecationWarning)
elif not isinstance(object_, str):
raise TypeError(f"object is not a string: {object_!r}")
return np.str_(object_)
| (self, object_) |
729,238 | tables.atom | fromarray | null | def fromarray(self, array):
length = len(array)
if length == 0:
return '' # ``array.view('U0')`` raises a `TypeError`
return array.view('U%d' % length).item()
| (self, array) |
729,239 | tables.atom | toarray | null | def toarray(self, object_):
if isinstance(object_, bytes):
warnings.warn("Storing bytestrings in VLUnicodeAtom is "
"deprecated.", DeprecationWarning)
elif not isinstance(object_, str):
raise TypeError(f"object is not a string: {object_!r}")
ustr = str(object_)
uarr = np.array(ustr, dtype='U')
return np.ndarray(
buffer=uarr, dtype=self.base.dtype, shape=len(ustr))
| (self, object_) |
729,247 | tables.path | check_name_validity | Check the validity of the `name` of a Node object, which more limited
than attribute names.
If the name is not valid, a ``ValueError`` is raised. If it is
valid but it can not be used with natural naming, a
`NaturalNameWarning` is issued.
>>> warnings.simplefilter("ignore")
>>> check_name_validity('a')
>>> check_name_validity('a_b')
>>> check_name_validity('a:b') # NaturalNameWarning
>>> check_name_validity('/a/b')
Traceback (most recent call last):
...
ValueError: the ``/`` character is not allowed in object names: '/a/b'
>>> check_name_validity('.')
Traceback (most recent call last):
...
ValueError: ``.`` is not allowed as an object name
>>> check_name_validity('')
Traceback (most recent call last):
...
ValueError: the empty string is not allowed as an object name
| def check_name_validity(name):
"""Check the validity of the `name` of a Node object, which more limited
than attribute names.
If the name is not valid, a ``ValueError`` is raised. If it is
valid but it can not be used with natural naming, a
`NaturalNameWarning` is issued.
>>> warnings.simplefilter("ignore")
>>> check_name_validity('a')
>>> check_name_validity('a_b')
>>> check_name_validity('a:b') # NaturalNameWarning
>>> check_name_validity('/a/b')
Traceback (most recent call last):
...
ValueError: the ``/`` character is not allowed in object names: '/a/b'
>>> check_name_validity('.')
Traceback (most recent call last):
...
ValueError: ``.`` is not allowed as an object name
>>> check_name_validity('')
Traceback (most recent call last):
...
ValueError: the empty string is not allowed as an object name
"""
check_attribute_name(name)
# Check whether `name` is a valid HDF5 name.
# http://hdfgroup.org/HDF5/doc/UG/03_Model.html#Structure
if name == '.':
raise ValueError("``.`` is not allowed as an object name")
elif '/' in name:
raise ValueError("the ``/`` character is not allowed "
"in object names: %r" % name)
| (name) |
729,250 | tables.file | copy_file | An easy way of copying one PyTables file to another.
This function allows you to copy an existing PyTables file named
srcfilename to another file called dstfilename. The source file
must exist and be readable. The destination file can be
overwritten in place if existing by asserting the overwrite
argument.
This function is a shorthand for the :meth:`File.copy_file` method,
which acts on an already opened file. kwargs takes keyword
arguments used to customize the copying process. See the
documentation of :meth:`File.copy_file` for a description of those
arguments.
| def copy_file(srcfilename, dstfilename, overwrite=False, **kwargs):
"""An easy way of copying one PyTables file to another.
This function allows you to copy an existing PyTables file named
srcfilename to another file called dstfilename. The source file
must exist and be readable. The destination file can be
overwritten in place if existing by asserting the overwrite
argument.
This function is a shorthand for the :meth:`File.copy_file` method,
which acts on an already opened file. kwargs takes keyword
arguments used to customize the copying process. See the
documentation of :meth:`File.copy_file` for a description of those
arguments.
"""
# Open the source file.
srcfileh = open_file(srcfilename, mode="r")
try:
# Copy it to the destination file.
srcfileh.copy_file(dstfilename, overwrite=overwrite, **kwargs)
finally:
# Close the source file.
srcfileh.close()
| (srcfilename, dstfilename, overwrite=False, **kwargs) |
729,251 | tables.description | descr_from_dtype | Get a description instance and byteorder from a (nested) NumPy dtype. | def descr_from_dtype(dtype_, ptparams=None):
"""Get a description instance and byteorder from a (nested) NumPy dtype."""
fields = {}
fbyteorder = '|'
for name in dtype_.names:
dtype, offset = dtype_.fields[name][:2]
kind = dtype.base.kind
byteorder = dtype.base.byteorder
if byteorder in '><=':
if fbyteorder not in ['|', byteorder]:
raise NotImplementedError(
"structured arrays with mixed byteorders "
"are not supported yet, sorry")
fbyteorder = byteorder
# Non-nested column
if kind in 'biufSUc':
col = Col.from_dtype(dtype, pos=offset, _offset=offset)
# Nested column
elif kind == 'V' and dtype.shape in [(), (1,)]:
if dtype.shape != ():
warnings.warn(
"nested descriptions will be converted to scalar")
col, _ = descr_from_dtype(dtype.base, ptparams=ptparams)
col._v_pos = offset
col._v_offset = offset
else:
raise NotImplementedError(
"structured arrays with columns with type description ``%s`` "
"are not supported yet, sorry" % dtype)
fields[name] = col
return Description(fields, ptparams=ptparams), fbyteorder
| (dtype_, ptparams=None) |
729,253 | tables.description | dtype_from_descr | Get a (nested) NumPy dtype from a description instance and byteorder.
The descr parameter can be a Description or IsDescription
instance, sub-class of IsDescription or a dictionary.
| def dtype_from_descr(descr, byteorder=None, ptparams=None):
"""Get a (nested) NumPy dtype from a description instance and byteorder.
The descr parameter can be a Description or IsDescription
instance, sub-class of IsDescription or a dictionary.
"""
if isinstance(descr, dict):
descr = Description(descr, ptparams=ptparams)
elif (type(descr) == type(IsDescription)
and issubclass(descr, IsDescription)):
descr = Description(descr().columns, ptparams=ptparams)
elif isinstance(descr, IsDescription):
descr = Description(descr.columns, ptparams=ptparams)
elif not isinstance(descr, Description):
raise ValueError('invalid description: %r' % descr)
dtype_ = descr._v_dtype
if byteorder and byteorder != '|':
dtype_ = dtype_.newbyteorder(byteorder)
return dtype_
| (descr, byteorder=None, ptparams=None) |
729,261 | tables | get_hdf5_version | null | def get_hdf5_version():
warnings.warn(
"the 'get_hdf5_version()' function is deprecated and could be "
"removed in future versions. Please use 'tables.hdf5_version'",
DeprecationWarning)
return hdf5_version
| () |
729,262 | tables | get_pytables_version | null | def get_pytables_version():
warnings.warn(
"the 'get_pytables_version()' function is deprecated and could be "
"removed in future versions. Please use 'tables.__version__'",
DeprecationWarning)
return __version__
| () |
729,277 | tables.file | open_file | Open a PyTables (or generic HDF5) file and return a File object.
Parameters
----------
filename : str
The name of the file (supports environment variable expansion).
It is suggested that file names have any of the .h5, .hdf or
.hdf5 extensions, although this is not mandatory.
mode : str
The mode to open the file. It can be one of the
following:
* *'r'*: Read-only; no data can be modified.
* *'w'*: Write; a new file is created (an existing file
with the same name would be deleted).
* *'a'*: Append; an existing file is opened for reading and
writing, and if the file does not exist it is created.
* *'r+'*: It is similar to 'a', but the file must already
exist.
title : str
If the file is to be created, a TITLE string attribute will be
set on the root group with the given value. Otherwise, the
title will be read from disk, and this will not have any effect.
root_uep : str
The root User Entry Point. This is a group in the HDF5 hierarchy
which will be taken as the starting point to create the object
tree. It can be whatever existing group in the file, named by
its HDF5 path. If it does not exist, an HDF5ExtError is issued.
Use this if you do not want to build the *entire* object tree,
but rather only a *subtree* of it.
.. versionchanged:: 3.0
The *rootUEP* parameter has been renamed into *root_uep*.
filters : Filters
An instance of the Filters (see :ref:`FiltersClassDescr`) class
that provides information about the desired I/O filters
applicable to the leaves that hang directly from the *root group*,
unless other filter properties are specified for these leaves.
Besides, if you do not specify filter properties for child groups,
they will inherit these ones, which will in turn propagate to
child nodes.
Notes
-----
In addition, it recognizes the (lowercase) names of parameters
present in :file:`tables/parameters.py` as additional keyword
arguments.
See :ref:`parameter_files` for a detailed info on the supported
parameters.
.. note::
If you need to deal with a large number of nodes in an
efficient way, please see :ref:`LRUOptim` for more info and
advices about the integrated node cache engine.
| def open_file(filename, mode="r", title="", root_uep="/", filters=None,
**kwargs):
"""Open a PyTables (or generic HDF5) file and return a File object.
Parameters
----------
filename : str
The name of the file (supports environment variable expansion).
It is suggested that file names have any of the .h5, .hdf or
.hdf5 extensions, although this is not mandatory.
mode : str
The mode to open the file. It can be one of the
following:
* *'r'*: Read-only; no data can be modified.
* *'w'*: Write; a new file is created (an existing file
with the same name would be deleted).
* *'a'*: Append; an existing file is opened for reading and
writing, and if the file does not exist it is created.
* *'r+'*: It is similar to 'a', but the file must already
exist.
title : str
If the file is to be created, a TITLE string attribute will be
set on the root group with the given value. Otherwise, the
title will be read from disk, and this will not have any effect.
root_uep : str
The root User Entry Point. This is a group in the HDF5 hierarchy
which will be taken as the starting point to create the object
tree. It can be whatever existing group in the file, named by
its HDF5 path. If it does not exist, an HDF5ExtError is issued.
Use this if you do not want to build the *entire* object tree,
but rather only a *subtree* of it.
.. versionchanged:: 3.0
The *rootUEP* parameter has been renamed into *root_uep*.
filters : Filters
An instance of the Filters (see :ref:`FiltersClassDescr`) class
that provides information about the desired I/O filters
applicable to the leaves that hang directly from the *root group*,
unless other filter properties are specified for these leaves.
Besides, if you do not specify filter properties for child groups,
they will inherit these ones, which will in turn propagate to
child nodes.
Notes
-----
In addition, it recognizes the (lowercase) names of parameters
present in :file:`tables/parameters.py` as additional keyword
arguments.
See :ref:`parameter_files` for a detailed info on the supported
parameters.
.. note::
If you need to deal with a large number of nodes in an
efficient way, please see :ref:`LRUOptim` for more info and
advices about the integrated node cache engine.
"""
filename = os.fspath(filename)
# XXX filename normalization ??
# Check already opened files
if _FILE_OPEN_POLICY == 'strict':
# This policy does not allow to open the same file multiple times
# even in read-only mode
if filename in _open_files:
raise ValueError(
"The file '%s' is already opened. "
"Please close it before reopening. "
"HDF5 v.%s, FILE_OPEN_POLICY = '%s'" % (
filename, utilsextension.get_hdf5_version(),
_FILE_OPEN_POLICY))
else:
for filehandle in _open_files.get_handlers_by_name(filename):
omode = filehandle.mode
# 'r' is incompatible with everything except 'r' itself
if mode == 'r' and omode != 'r':
raise ValueError(
"The file '%s' is already opened, but "
"not in read-only mode (as requested)." % filename)
# 'a' and 'r+' are compatible with everything except 'r'
elif mode in ('a', 'r+') and omode == 'r':
raise ValueError(
"The file '%s' is already opened, but "
"in read-only mode. Please close it before "
"reopening in append mode." % filename)
# 'w' means that we want to destroy existing contents
elif mode == 'w':
raise ValueError(
"The file '%s' is already opened. Please "
"close it before reopening in write mode." % filename)
# Finally, create the File instance, and return it
return File(filename, mode, title, root_uep, filters, **kwargs)
| (filename, mode='r', title='', root_uep='/', filters=None, **kwargs) |
729,283 | tables.tests.common | print_versions | Print all the versions of software that PyTables relies on. | def print_versions():
"""Print all the versions of software that PyTables relies on."""
print('-=' * 38)
print("PyTables version: %s" % tb.__version__)
print("HDF5 version: %s" % tb.which_lib_version("hdf5")[1])
print("NumPy version: %s" % np.__version__)
tinfo = tb.which_lib_version("zlib")
if ne.use_vml:
# Get only the main version number and strip out all the rest
vml_version = ne.get_vml_version()
vml_version = re.findall("[0-9.]+", vml_version)[0]
vml_avail = "using VML/MKL %s" % vml_version
else:
vml_avail = "not using Intel's VML/MKL"
print(f"Numexpr version: {ne.__version__} ({vml_avail})")
if tinfo is not None:
print(f"Zlib version: {tinfo[1]} (in Python interpreter)")
tinfo = tb.which_lib_version("lzo")
if tinfo is not None:
print("LZO version: {} ({})".format(tinfo[1], tinfo[2]))
tinfo = tb.which_lib_version("bzip2")
if tinfo is not None:
print("BZIP2 version: {} ({})".format(tinfo[1], tinfo[2]))
tinfo = tb.which_lib_version("blosc")
if tinfo is not None:
blosc_date = tinfo[2].split()[1]
print("Blosc version: {} ({})".format(tinfo[1], blosc_date))
blosc_cinfo = tb.blosc_get_complib_info()
blosc_cinfo = [
"{} ({})".format(k, v[1]) for k, v in sorted(blosc_cinfo.items())
]
print("Blosc compressors: %s" % ', '.join(blosc_cinfo))
blosc_finfo = ['shuffle', 'bitshuffle']
print("Blosc filters: %s" % ', '.join(blosc_finfo))
tinfo = tb.which_lib_version("blosc2")
if tinfo is not None:
blosc2_date = tinfo[2].split()[1]
print("Blosc2 version: {} ({})".format(tinfo[1], blosc2_date))
blosc2_cinfo = tb.blosc2_get_complib_info()
blosc2_cinfo = [
"{} ({})".format(k, v[1]) for k, v in sorted(blosc2_cinfo.items())
]
print("Blosc2 compressors: %s" % ', '.join(blosc2_cinfo))
blosc2_finfo = ['shuffle', 'bitshuffle']
print("Blosc2 filters: %s" % ', '.join(blosc2_finfo))
try:
from Cython import __version__ as cython_version
print('Cython version: %s' % cython_version)
except Exception:
pass
print('Python version: %s' % sys.version)
print('Platform: %s' % platform.platform())
# if os.name == 'posix':
# (sysname, nodename, release, version, machine) = os.uname()
# print('Platform: %s-%s' % (sys.platform, machine))
print('Byte-ordering: %s' % sys.byteorder)
print('Detected cores: %s' % tb.utils.detect_number_of_cores())
print('Default encoding: %s' % sys.getdefaultencoding())
print('Default FS encoding: %s' % sys.getfilesystemencoding())
print('Default locale: (%s, %s)' % locale.getdefaultlocale())
print('-=' * 38)
# This should improve readability whan tests are run by CI tools
sys.stdout.flush()
| () |
729,287 | tables.flavor | restrict_flavors | Disable all flavors except those in keep.
Providing an empty keep sequence implies disabling all flavors (but the
internal one). If the sequence is not specified, only optional flavors are
disabled.
.. important:: Once you disable a flavor, it can not be enabled again.
| def restrict_flavors(keep=('python',)):
"""Disable all flavors except those in keep.
Providing an empty keep sequence implies disabling all flavors (but the
internal one). If the sequence is not specified, only optional flavors are
disabled.
.. important:: Once you disable a flavor, it can not be enabled again.
"""
remove = set(all_flavors) - set(keep) - {internal_flavor}
for flavor in remove:
_disable_flavor(flavor)
| (keep=('python',)) |
729,288 | tables.description | same_position | Decorate `oldmethod` to also compare the `_v_pos` attribute. | def same_position(oldmethod):
"""Decorate `oldmethod` to also compare the `_v_pos` attribute."""
def newmethod(self, other):
try:
other._v_pos
except AttributeError:
return False # not a column definition
return self._v_pos == other._v_pos and oldmethod(self, other)
newmethod.__name__ = oldmethod.__name__
newmethod.__doc__ = oldmethod.__doc__
return newmethod
| (oldmethod) |
729,289 | tables.atom | split_type | Split a PyTables type into a PyTables kind and an item size.
Returns a tuple of (kind, itemsize). If no item size is present in the type
(in the form of a precision), the returned item size is None::
>>> split_type('int32')
('int', 4)
>>> split_type('string')
('string', None)
>>> split_type('int20')
Traceback (most recent call last):
...
ValueError: precision must be a multiple of 8: 20
>>> split_type('foo bar')
Traceback (most recent call last):
...
ValueError: malformed type: 'foo bar'
| def split_type(type):
"""Split a PyTables type into a PyTables kind and an item size.
Returns a tuple of (kind, itemsize). If no item size is present in the type
(in the form of a precision), the returned item size is None::
>>> split_type('int32')
('int', 4)
>>> split_type('string')
('string', None)
>>> split_type('int20')
Traceback (most recent call last):
...
ValueError: precision must be a multiple of 8: 20
>>> split_type('foo bar')
Traceback (most recent call last):
...
ValueError: malformed type: 'foo bar'
"""
match = _type_re.match(type)
if not match:
raise ValueError("malformed type: %r" % type)
kind, precision = match.groups()
itemsize = None
if precision:
precision = int(precision)
itemsize, remainder = divmod(precision, 8)
if remainder: # 0 could be a valid item size
raise ValueError("precision must be a multiple of 8: %d"
% precision)
return (kind, itemsize)
| (type) |
729,292 | tables.tests.test_suite | test | Run all the tests in the test suite.
If *verbose* is set, the test suite will emit messages with full
verbosity (not recommended unless you are looking into a certain
problem).
If *heavy* is set, the test suite will be run in *heavy* mode (you
should be careful with this because it can take a lot of time and
resources from your computer).
Return 0 (os.EX_OK) if all tests pass, 1 in case of failure
| def test(verbose=False, heavy=False):
"""Run all the tests in the test suite.
If *verbose* is set, the test suite will emit messages with full
verbosity (not recommended unless you are looking into a certain
problem).
If *heavy* is set, the test suite will be run in *heavy* mode (you
should be careful with this because it can take a lot of time and
resources from your computer).
Return 0 (os.EX_OK) if all tests pass, 1 in case of failure
"""
common.print_versions()
common.print_heavy(heavy)
# What a context this is!
# oldverbose, common.verbose = common.verbose, verbose
oldheavy, common.heavy = common.heavy, heavy
try:
result = common.unittest.TextTestRunner(
verbosity=1 + int(verbose)).run(suite())
if result.wasSuccessful():
return 0
else:
return 1
finally:
# common.verbose = oldverbose
common.heavy = oldheavy # there are pretty young heavies, too ;)
| (verbose=False, heavy=False) |
729,300 | cryptography.hazmat.primitives.ciphers.algorithms | AES | null | class AES(BlockCipherAlgorithm):
name = "AES"
block_size = 128
# 512 added to support AES-256-XTS, which uses 512-bit keys
key_sizes = frozenset([128, 192, 256, 512])
def __init__(self, key: bytes):
self.key = _verify_key_size(self, key)
@property
def key_size(self) -> int:
return len(self.key) * 8
| (key: bytes) |
729,301 | cryptography.hazmat.primitives.ciphers.algorithms | __init__ | null | def __init__(self, key: bytes):
self.key = _verify_key_size(self, key)
| (self, key: bytes) |
729,302 | tinytuya.core | AESCipher | null | class AESCipher(_AESCipher_PyCrypto):
CRYPTOLIB = CRYPTOLIB
CRYPTOLIB_VER = '.'.join( [str(x) for x in Crypto.version_info] )
CRYPTOLIB_HAS_GCM = getattr( AES, 'MODE_GCM', False ) # only PyCryptodome supports GCM, PyCrypto does not
| (key) |
729,304 | tinytuya.core | _pad | null | @staticmethod
def _pad(s, bs):
padnum = bs - len(s) % bs
return s + padnum * chr(padnum).encode()
| (s, bs) |
729,305 | tinytuya.core | _unpad | null | @staticmethod
def _unpad(s, verify_padding=False):
padlen = ord(s[-1:])
if padlen < 1 or padlen > 16:
raise ValueError("invalid padding length byte")
if verify_padding and s[-padlen:] != (padlen * chr(padlen).encode()):
raise ValueError("invalid padding data")
return s[:-padlen]
| (s, verify_padding=False) |
729,306 | tinytuya.core | decrypt | null | def decrypt(self, enc, use_base64=True, decode_text=True, verify_padding=False, iv=False, header=None, tag=None):
if not iv:
if use_base64:
enc = base64.b64decode(enc)
if len(enc) % 16 != 0:
raise ValueError("invalid length")
if iv:
iv, enc = self.get_decryption_iv( iv, enc )
if tag is None:
decryptor = Crypto( AES(self.key), Crypto_modes.CTR(iv + b'\x00\x00\x00\x02') ).decryptor()
else:
decryptor = Crypto( AES(self.key), Crypto_modes.GCM(iv, tag) ).decryptor()
if header and (tag is not None):
decryptor.authenticate_additional_data( header )
raw = decryptor.update( enc ) + decryptor.finalize()
else:
decryptor = Crypto( AES(self.key), Crypto_modes.ECB() ).decryptor()
raw = decryptor.update( enc ) + decryptor.finalize()
raw = self._unpad(raw, verify_padding)
return raw.decode("utf-8") if decode_text else raw
| (self, enc, use_base64=True, decode_text=True, verify_padding=False, iv=False, header=None, tag=None) |
729,307 | tinytuya.core | encrypt | null | def encrypt(self, raw, use_base64=True, pad=True, iv=False, header=None): # pylint: disable=W0621
if iv: # initialization vector or nonce (number used once)
iv = self.get_encryption_iv( iv )
encryptor = Crypto( AES(self.key), Crypto_modes.GCM(iv) ).encryptor()
if header:
encryptor.authenticate_additional_data(header)
crypted_text = encryptor.update(raw) + encryptor.finalize()
crypted_text = iv + crypted_text + encryptor.tag
else:
if pad: raw = self._pad(raw, 16)
encryptor = Crypto( AES(self.key), Crypto_modes.ECB() ).encryptor()
crypted_text = encryptor.update(raw) + encryptor.finalize()
return base64.b64encode(crypted_text) if use_base64 else crypted_text
| (self, raw, use_base64=True, pad=True, iv=False, header=None) |
729,308 | tinytuya.BulbDevice | BulbDevice |
Represents a Tuya based Smart Light/Bulb.
This class supports two types of bulbs with different DPS mappings and functions:
Type A - Uses DPS index 1-5
Type B - Uses DPS index 20-27 (no index 1)
Type C - Same as Type A except that it is using DPS 2 for brightness, which ranges from 0-1000. These are the Feit branded dimmers found at Costco.
| class BulbDevice(Device):
"""
Represents a Tuya based Smart Light/Bulb.
This class supports two types of bulbs with different DPS mappings and functions:
Type A - Uses DPS index 1-5
Type B - Uses DPS index 20-27 (no index 1)
Type C - Same as Type A except that it is using DPS 2 for brightness, which ranges from 0-1000. These are the Feit branded dimmers found at Costco.
"""
# Two types of Bulbs - TypeA uses DPS 1-5, TypeB uses DPS 20-24
DPS_INDEX_ON = {"A": "1", "B": "20", "C": "1"}
DPS_INDEX_MODE = {"A": "2", "B": "21", "C": "1"}
DPS_INDEX_BRIGHTNESS = {"A": "3", "B": "22", "C": "2"}
DPS_INDEX_COLOURTEMP = {"A": "4", "B": "23", "C": None}
DPS_INDEX_COLOUR = {"A": "5", "B": "24", "C": None}
DPS_INDEX_SCENE = {"A": "2", "B": "25", "C": None}
DPS_INDEX_TIMER = {"A": None, "B": "26", "C": None}
DPS_INDEX_MUSIC = {"A": None, "B": "27", "C": None}
DPS = "dps"
DPS_MODE_WHITE = "white"
DPS_MODE_COLOUR = "colour"
DPS_MODE_SCENE = "scene"
DPS_MODE_MUSIC = "music"
DPS_MODE_SCENE_1 = "scene_1" # nature
DPS_MODE_SCENE_2 = "scene_2"
DPS_MODE_SCENE_3 = "scene_3" # rave
DPS_MODE_SCENE_4 = "scene_4" # rainbow
DPS_2_STATE = {
"1": "is_on",
"2": "mode",
"3": "brightness",
"4": "colourtemp",
"5": "colour",
"20": "is_on",
"21": "mode",
"22": "brightness",
"23": "colourtemp",
"24": "colour",
}
# Set Default Bulb Types
bulb_type = "A"
has_brightness = False
has_colourtemp = False
has_colour = False
def __init__(self, *args, **kwargs):
# set the default version to None so we do not immediately connect and call status()
if 'version' not in kwargs or not kwargs['version']:
kwargs['version'] = None
super(BulbDevice, self).__init__(*args, **kwargs)
@staticmethod
def _rgb_to_hexvalue(r, g, b, bulb="A"):
"""
Convert an RGB value to the hex representation expected by Tuya Bulb.
Index (DPS_INDEX_COLOUR) is assumed to be in the format:
(Type A) Index: 5 in hex format: rrggbb0hhhssvv
(Type B) Index: 24 in hex format: hhhhssssvvvv
While r, g and b are just hexadecimal values of the corresponding
Red, Green and Blue values, the h, s and v values (which are values
between 0 and 1) are scaled:
Type A: 360 (h) and 255 (s and v)
Type B: 360 (h) and 1000 (s and v)
Args:
r(int): Value for the colour red as int from 0-255.
g(int): Value for the colour green as int from 0-255.
b(int): Value for the colour blue as int from 0-255.
"""
rgb = [r, g, b]
hsv = colorsys.rgb_to_hsv(rgb[0] / 255.0, rgb[1] / 255.0, rgb[2] / 255.0)
# Bulb Type A
if bulb == "A":
# h:0-360,s:0-255,v:0-255|hsv|
hexvalue = ""
for value in rgb:
temp = str(hex(int(value))).replace("0x", "")
if len(temp) == 1:
temp = "0" + temp
hexvalue = hexvalue + temp
hsvarray = [int(hsv[0] * 360), int(hsv[1] * 255), int(hsv[2] * 255)]
hexvalue_hsv = ""
for value in hsvarray:
temp = str(hex(int(value))).replace("0x", "")
if len(temp) == 1:
temp = "0" + temp
hexvalue_hsv = hexvalue_hsv + temp
if len(hexvalue_hsv) == 7:
hexvalue = hexvalue + "0" + hexvalue_hsv
else:
hexvalue = hexvalue + "00" + hexvalue_hsv
# Bulb Type B
if bulb == "B":
# h:0-360,s:0-1000,v:0-1000|hsv|
hexvalue = ""
hsvarray = [int(hsv[0] * 360), int(hsv[1] * 1000), int(hsv[2] * 1000)]
for value in hsvarray:
temp = str(hex(int(value))).replace("0x", "")
while len(temp) < 4:
temp = "0" + temp
hexvalue = hexvalue + temp
return hexvalue
@staticmethod
def _hexvalue_to_rgb(hexvalue, bulb="A"):
"""
Converts the hexvalue used by Tuya for colour representation into
an RGB value.
Args:
hexvalue(string): The hex representation generated by BulbDevice._rgb_to_hexvalue()
"""
if bulb == "A":
r = int(hexvalue[0:2], 16)
g = int(hexvalue[2:4], 16)
b = int(hexvalue[4:6], 16)
if bulb == "B":
# hexvalue is in hsv
h = float(int(hexvalue[0:4], 16) / 360.0)
s = float(int(hexvalue[4:8], 16) / 1000.0)
v = float(int(hexvalue[8:12], 16) / 1000.0)
rgb = colorsys.hsv_to_rgb(h, s, v)
r = int(rgb[0] * 255)
g = int(rgb[1] * 255)
b = int(rgb[2] * 255)
return (r, g, b)
@staticmethod
def _hexvalue_to_hsv(hexvalue, bulb="A"):
"""
Converts the hexvalue used by Tuya for colour representation into
an HSV value.
Args:
hexvalue(string): The hex representation generated by BulbDevice._rgb_to_hexvalue()
"""
if bulb == "A":
h = int(hexvalue[7:10], 16) / 360.0
s = int(hexvalue[10:12], 16) / 255.0
v = int(hexvalue[12:14], 16) / 255.0
if bulb == "B":
# hexvalue is in hsv
h = int(hexvalue[0:4], 16) / 360.0
s = int(hexvalue[4:8], 16) / 1000.0
v = int(hexvalue[8:12], 16) / 1000.0
return (h, s, v)
def set_version(self, version): # pylint: disable=W0621
"""
Set the Tuya device version 3.1 or 3.3 for BulbDevice
Attempt to determine BulbDevice Type: A or B based on:
Type A has keys 1-5 (default)
Type B has keys 20-29
Type C is Feit type bulbs from costco
"""
super(BulbDevice, self).set_version(version)
# Try to determine type of BulbDevice Type based on DPS indexes
status = self.status()
if status is not None:
if "dps" in status:
if "1" not in status["dps"]:
self.bulb_type = "B"
if self.DPS_INDEX_BRIGHTNESS[self.bulb_type] in status["dps"]:
self.has_brightness = True
if self.DPS_INDEX_COLOURTEMP[self.bulb_type] in status["dps"]:
self.has_colourtemp = True
if self.DPS_INDEX_COLOUR[self.bulb_type] in status["dps"]:
self.has_colour = True
else:
self.bulb_type = "B"
else:
# response has no dps
self.bulb_type = "B"
log.debug("bulb type set to %s", self.bulb_type)
def turn_on(self, switch=0, nowait=False):
"""Turn the device on"""
if switch == 0:
switch = self.DPS_INDEX_ON[self.bulb_type]
self.set_status(True, switch, nowait=nowait)
def turn_off(self, switch=0, nowait=False):
"""Turn the device on"""
if switch == 0:
switch = self.DPS_INDEX_ON[self.bulb_type]
self.set_status(False, switch, nowait=nowait)
def set_bulb_type(self, type):
self.bulb_type = type
def set_mode(self, mode="white", nowait=False):
"""
Set bulb mode
Args:
mode(string): white,colour,scene,music
nowait(bool): True to send without waiting for response.
"""
payload = self.generate_payload(
CONTROL, {self.DPS_INDEX_MODE[self.bulb_type]: mode}
)
data = self._send_receive(payload, getresponse=(not nowait))
return data
def set_scene(self, scene, nowait=False):
"""
Set to scene mode
Args:
scene(int): Value for the scene as int from 1-4.
nowait(bool): True to send without waiting for response.
"""
if not 1 <= scene <= 4:
return error_json(
ERR_RANGE, "set_scene: The value for scene needs to be between 1 and 4."
)
if scene == 1:
s = self.DPS_MODE_SCENE_1
elif scene == 2:
s = self.DPS_MODE_SCENE_2
elif scene == 3:
s = self.DPS_MODE_SCENE_3
else:
s = self.DPS_MODE_SCENE_4
payload = self.generate_payload(
CONTROL, {self.DPS_INDEX_MODE[self.bulb_type]: s}
)
data = self._send_receive(payload, getresponse=(not nowait))
return data
def set_colour(self, r, g, b, nowait=False):
"""
Set colour of an rgb bulb.
Args:
r(int): Value for the colour Red as int from 0-255.
g(int): Value for the colour Green as int from 0-255.
b(int): Value for the colour Blue as int from 0-255.
nowait(bool): True to send without waiting for response.
"""
if not self.has_colour:
log.debug("set_colour: Device does not appear to support color.")
# return error_json(ERR_FUNCTION, "set_colour: Device does not support color.")
if not 0 <= r <= 255:
return error_json(
ERR_RANGE,
"set_colour: The value for red needs to be between 0 and 255.",
)
if not 0 <= g <= 255:
return error_json(
ERR_RANGE,
"set_colour: The value for green needs to be between 0 and 255.",
)
if not 0 <= b <= 255:
return error_json(
ERR_RANGE,
"set_colour: The value for blue needs to be between 0 and 255.",
)
hexvalue = BulbDevice._rgb_to_hexvalue(r, g, b, self.bulb_type)
payload = self.generate_payload(
CONTROL,
{
self.DPS_INDEX_MODE[self.bulb_type]: self.DPS_MODE_COLOUR,
self.DPS_INDEX_COLOUR[self.bulb_type]: hexvalue,
},
)
data = self._send_receive(payload, getresponse=(not nowait))
return data
def set_hsv(self, h, s, v, nowait=False):
"""
Set colour of an rgb bulb using h, s, v.
Args:
h(float): colour Hue as float from 0-1
s(float): colour Saturation as float from 0-1
v(float): colour Value as float from 0-1
nowait(bool): True to send without waiting for response.
"""
if not self.has_colour:
log.debug("set_hsv: Device does not appear to support color.")
# return error_json(ERR_FUNCTION, "set_hsv: Device does not support color.")
if not 0 <= h <= 1.0:
return error_json(
ERR_RANGE, "set_hsv: The value for Hue needs to be between 0 and 1."
)
if not 0 <= s <= 1.0:
return error_json(
ERR_RANGE,
"set_hsv: The value for Saturation needs to be between 0 and 1.",
)
if not 0 <= v <= 1.0:
return error_json(
ERR_RANGE,
"set_hsv: The value for Value needs to be between 0 and 1.",
)
(r, g, b) = colorsys.hsv_to_rgb(h, s, v)
hexvalue = BulbDevice._rgb_to_hexvalue(
r * 255.0, g * 255.0, b * 255.0, self.bulb_type
)
payload = self.generate_payload(
CONTROL,
{
self.DPS_INDEX_MODE[self.bulb_type]: self.DPS_MODE_COLOUR,
self.DPS_INDEX_COLOUR[self.bulb_type]: hexvalue,
},
)
data = self._send_receive(payload, getresponse=(not nowait))
return data
def set_white_percentage(self, brightness=100, colourtemp=0, nowait=False):
"""
Set white coloured theme of an rgb bulb.
Args:
brightness(int): Value for the brightness in percent (0-100)
colourtemp(int): Value for the colour temperature in percent (0-100)
nowait(bool): True to send without waiting for response.
"""
# Brightness
if not 0 <= brightness <= 100:
return error_json(
ERR_RANGE,
"set_white_percentage: Brightness percentage needs to be between 0 and 100.",
)
b = int(25 + (255 - 25) * brightness / 100)
if self.bulb_type == "B":
b = int(10 + (1000 - 10) * brightness / 100)
# Colourtemp
if not 0 <= colourtemp <= 100:
return error_json(
ERR_RANGE,
"set_white_percentage: Colourtemp percentage needs to be between 0 and 100.",
)
c = int(255 * colourtemp / 100)
if self.bulb_type == "B":
c = int(1000 * colourtemp / 100)
data = self.set_white(b, c, nowait=nowait)
return data
def set_white(self, brightness=-1, colourtemp=-1, nowait=False):
"""
Set white coloured theme of an rgb bulb.
Args:
brightness(int): Value for the brightness (A:25-255 or B:10-1000)
colourtemp(int): Value for the colour temperature (A:0-255, B:0-1000).
nowait(bool): True to send without waiting for response.
Default: Max Brightness and Min Colourtemp
"""
# Brightness (default Max)
if brightness < 0:
brightness = 255
if self.bulb_type == "B":
brightness = 1000
if self.bulb_type == "A" and not 25 <= brightness <= 255:
return error_json(
ERR_RANGE, "set_white: The brightness needs to be between 25 and 255."
)
if self.bulb_type == "B" and not 10 <= brightness <= 1000:
return error_json(
ERR_RANGE, "set_white: The brightness needs to be between 10 and 1000."
)
# Colourtemp (default Min)
if colourtemp < 0:
colourtemp = 0
if self.bulb_type == "A" and not 0 <= colourtemp <= 255:
return error_json(
ERR_RANGE,
"set_white: The colour temperature needs to be between 0 and 255.",
)
if self.bulb_type == "B" and not 0 <= colourtemp <= 1000:
return error_json(
ERR_RANGE,
"set_white: The colour temperature needs to be between 0 and 1000.",
)
payload = self.generate_payload(
CONTROL,
{
self.DPS_INDEX_MODE[self.bulb_type]: self.DPS_MODE_WHITE,
self.DPS_INDEX_BRIGHTNESS[self.bulb_type]: brightness,
self.DPS_INDEX_COLOURTEMP[self.bulb_type]: colourtemp,
},
)
data = self._send_receive(payload, getresponse=(not nowait))
return data
def set_brightness_percentage(self, brightness=100, nowait=False):
"""
Set the brightness value of an rgb bulb.
Args:
brightness(int): Value for the brightness in percent (0-100)
nowait(bool): True to send without waiting for response.
"""
if not 0 <= brightness <= 100:
return error_json(
ERR_RANGE,
"set_brightness_percentage: Brightness percentage needs to be between 0 and 100.",
)
b = int(25 + (255 - 25) * brightness / 100)
if self.bulb_type == "B":
b = int(10 + (1000 - 10) * brightness / 100)
data = self.set_brightness(b, nowait=nowait)
return data
def set_brightness(self, brightness, nowait=False):
"""
Set the brightness value of an rgb bulb.
Args:
brightness(int): Value for the brightness (25-255).
nowait(bool): True to send without waiting for response.
"""
if self.bulb_type == "A" and not 25 <= brightness <= 255:
return error_json(
ERR_RANGE,
"set_brightness: The brightness needs to be between 25 and 255.",
)
if self.bulb_type == "B" and not 10 <= brightness <= 1000:
return error_json(
ERR_RANGE,
"set_brightness: The brightness needs to be between 10 and 1000.",
)
# Determine which mode bulb is in and adjust accordingly
state = self.state()
data = None
if "mode" in state:
if state["mode"] == "white":
# for white mode use DPS for brightness
if not self.has_brightness:
log.debug("set_brightness: Device does not appear to support brightness.")
# return error_json(ERR_FUNCTION, "set_brightness: Device does not support brightness.")
payload = self.generate_payload(
CONTROL, {self.DPS_INDEX_BRIGHTNESS[self.bulb_type]: brightness}
)
data = self._send_receive(payload, getresponse=(not nowait))
if state["mode"] == "colour":
# for colour mode use hsv to increase brightness
if self.bulb_type == "A":
value = brightness / 255.0
else:
value = brightness / 1000.0
(h, s, v) = self.colour_hsv()
data = self.set_hsv(h, s, value, nowait=nowait)
if data is not None or nowait is True:
return data
else:
return error_json(ERR_STATE, "set_brightness: Unknown bulb state.")
def set_colourtemp_percentage(self, colourtemp=100, nowait=False):
"""
Set the colour temperature of an rgb bulb.
Args:
colourtemp(int): Value for the colour temperature in percentage (0-100).
nowait(bool): True to send without waiting for response.
"""
if not 0 <= colourtemp <= 100:
return error_json(
ERR_RANGE,
"set_colourtemp_percentage: Colourtemp percentage needs to be between 0 and 100.",
)
c = int(255 * colourtemp / 100)
if self.bulb_type == "B":
c = int(1000 * colourtemp / 100)
data = self.set_colourtemp(c, nowait=nowait)
return data
def set_colourtemp(self, colourtemp, nowait=False):
"""
Set the colour temperature of an rgb bulb.
Args:
colourtemp(int): Value for the colour temperature (0-255).
nowait(bool): True to send without waiting for response.
"""
if not self.has_colourtemp:
log.debug("set_colourtemp: Device does not appear to support colortemp.")
# return error_json(ERR_FUNCTION, "set_colourtemp: Device does not support colortemp.")
if self.bulb_type == "A" and not 0 <= colourtemp <= 255:
return error_json(
ERR_RANGE,
"set_colourtemp: The colour temperature needs to be between 0 and 255.",
)
if self.bulb_type == "B" and not 0 <= colourtemp <= 1000:
return error_json(
ERR_RANGE,
"set_colourtemp: The colour temperature needs to be between 0 and 1000.",
)
payload = self.generate_payload(
CONTROL, {self.DPS_INDEX_COLOURTEMP[self.bulb_type]: colourtemp}
)
data = self._send_receive(payload, getresponse=(not nowait))
return data
def brightness(self):
"""Return brightness value"""
return self.status()[self.DPS][self.DPS_INDEX_BRIGHTNESS[self.bulb_type]]
def colourtemp(self):
"""Return colour temperature"""
return self.status()[self.DPS][self.DPS_INDEX_COLOURTEMP[self.bulb_type]]
def colour_rgb(self):
"""Return colour as RGB value"""
hexvalue = self.status()[self.DPS][self.DPS_INDEX_COLOUR[self.bulb_type]]
return BulbDevice._hexvalue_to_rgb(hexvalue, self.bulb_type)
def colour_hsv(self):
"""Return colour as HSV value"""
hexvalue = self.status()[self.DPS][self.DPS_INDEX_COLOUR[self.bulb_type]]
return BulbDevice._hexvalue_to_hsv(hexvalue, self.bulb_type)
def state(self):
"""Return state of Bulb"""
status = self.status()
state = {}
if not status:
return error_json(ERR_JSON, "state: empty response")
if "Error" in status.keys():
return error_json(ERR_JSON, status["Error"])
if self.DPS not in status.keys():
return error_json(ERR_JSON, "state: no data points")
for key in status[self.DPS].keys():
if key in self.DPS_2_STATE:
state[self.DPS_2_STATE[key]] = status[self.DPS][key]
return state
| (*args, **kwargs) |
729,309 | tinytuya.core | __del__ | null | def __del__(self):
# In case we have a lingering socket connection, close it
try:
if self.socket:
# self.socket.shutdown(socket.SHUT_RDWR)
self.socket.close()
self.socket = None
except:
pass
| (self) |