Variables

A class and utilities for encoding variable objects.

The Variables class is intended to be used as an attribute of other classes, such as DiscreteQuadraticModel and SampleSet.

The requirements for the class are:
  • Have a minimal memory footprint when the variables are labeled [0, n)

  • Behave like a list for iteration and getting items

  • Behave like a set for determining if it contains an item

  • Constant time for finding the index of an item

Variables Class

class Variables[source]

Set-like and list-like variables tracking.

Parameters

iterable (iterable[Variable], optional) – An iterable of labels. Duplicate labels are ignored. All labels must be hashable.

Examples

The Variables object encodes an ordered set of variables.

>>> variables = dimod.variables.Variables(['a', 'b', 0, 1])
>>> print(variables)
Variables(['a', 'b', 0, 1])

Variables is a sequence.

>>> variables[0]  # O(1) element access using integer indices
'a'
>>> len(variables)  # defines a length
4

Unlike most other sequence types, Variables provides O(1) lookup for the index of an element.

>>> 0 in variables  # O(1) lookup
True
>>> variables.index('b')  # O(1) lookup
1

Therefore Variables is also a set.

>>> variables & [0, 'a', 'f']
Variables([0, 'a'])

Variables inherits from Sequence and Set so it inherits all of the provided mixin methods.

>>> list(reversed(variables))
[1, 0, 'b', 'a']
>>> variables.count('b')
1
>>> variables.count('hello')
0

Properties

is_range

Return True if the variables are labeled [0,n).

Methods

index

Return the index of v.

count

Return the number of times v appears in the variables.

to_serializable()

Return an object that is JSON-serializable.

Mutation Methods

Caution

The Variables class comes with a number of semi-public methods that allow other classes to manipulate its contents. These are intended to be used by parent classes, not by the user. Modifying a Variables object that is an attribute of a class results in undefined behaviour.

_append

Append a new variable.

_clear

Remove all variables.

_extend

Add new variables.

_pop

Remove the last variable.

_relabel

Relabel the variables in-place.

_relabel_as_integers

Relabel the variables as integers in-place.

_remove

Remove the given variable.