Symbols#

Symbols are a model’s decision variables, intermediate variables, constants, and mathematical operations.

See the Symbols section for an introduction to working with symbols.

All symbols listed in the Model Symbols subsection below inherit from the Symbol class and, for most mathematical symbols, the ArraySymbol class.

Symbol#

All symbols inherit from the Symbol class and therefore inherit its methods.

class Symbol[source]#

Base class for symbols.

Symbols are a model’s decision variables, intermediate variables, constants, and mathematical operations. Each symbol corresponds to a node in the directed acyclic graph representing the problem.

equals(other)[source]#

Compare whether two symbols are identical.

Equal symbols represent the same quantity in the model.

Parameters:

other (Symbol) – A symbol for comparison.

Returns:

True if the symbols are identical.

Return type:

bool

Note that comparing symbols across models is expensive.

Examples

This example creates two symbols that are the sum of the same two IntegerVariable symbols and a third that is the difference between them, and checks equality.

>>> from dwave.optimization import Model
>>> model = Model()
>>> i = model.integer(3)
>>> j = model.integer(3)
>>> a = i + j
>>> b = i + j
>>> c = i - j
>>> print(a.equals(a), a.equals(b), a.equals(c))
True True False

See also

maybe_equals(): A faster alternative for equality testing but that can return false positives.

has_state(index=0)[source]#

Return the initialization status of the indexed state.

Parameters:

index (int, optional, default=0) – Index of the queried state.

Returns:

True if the state is initialized.

Return type:

bool

Examples

>>> from dwave.optimization import Model
>>> model = Model()
>>> i = model.integer(3, lower_bound=0, upper_bound=20)
>>> with model.lock():
...     model.states.resize(5)
...     i.set_state(1, [2, 4, 15])
...     print(i.has_state(0), i.has_state(1))
False True

See also

reset_state()

id()[source]#

Return the “identity” of the underlying node.

This identity is unique to the underlying node, rather than the identity of the Python object representing it. Therefore, symbol.id() is not the same as id(symbol)!

Returns:

Identity of the underlying node.

Return type:

int

Examples

>>> from dwave.optimization import Model
>>> model = Model()
>>> a = model.binary()
>>> aa, = model.iter_symbols()
>>> assert a.id() == aa.id()
>>> assert id(a) != id(aa)

While symbols are not hashable, the .id() is.

>>> model = Model()
>>> x = model.integer()
>>> seen = {x.id()}

See also

iter_predecessors()[source]#

Iterate over a symbol’s predecessors in the model.

Yields:

The symbol’s predecessors.

Examples

This example constructs a \(b = \sum a\) model, where \(a\) is a multiplication of two symbols, and iterates over the predecessors of \(b\) (which is just \(a\)).

>>> from dwave.optimization.model import Model
>>> model = Model()
>>> i = model.integer((2, 2), upper_bound=20)
>>> c = model.constant([[21, 11], [10, 4]])
>>> a = c * i
>>> b = a.sum()
>>> a.equals(next(b.iter_predecessors()))
True
Image of the model constructed in this example

Fig. 257 Visualization of the model as a directed acyclic graph. See the to_networkx() function for information on visualizing models.#

iter_successors()[source]#

Iterate over a symbol’s successors in the model.

Yields:

The symbol’s successors.

Examples

This example constructs a \(y = x + 5\) model and iterates over the successors of \(x\) (which is just \(y\)).

>>> from dwave.optimization.model import Model
>>> model = Model()
>>> x = model.binary()
>>> y = x + 5
>>> y.equals(next(x.iter_successors()))
True
Image of the model constructed in this example

Fig. 258 Visualization of the model as a directed acyclic graph. See the to_networkx() function for information on visualizing models.#

maybe_equals(other)[source]#

Compare to another symbol.

This method exists because a complete equality test can be expensive.

Parameters:

other (Symbol) – Another symbol in the model’s directed acyclic graph.

Returns:

Supported return values are the following.

  • 0—Not equal (with certainty)

  • 1—Might be equal (no guarantees); a complete equality test is necessary

  • 2—Are equal (with certainty)

Return type:

int

Examples

This example compares IntegerVariable symbols of different sizes.

>>> from dwave.optimization import Model
>>> model = Model()
>>> i = model.integer(3, lower_bound=0, upper_bound=20)
>>> j = model.integer(3, lower_bound=-10, upper_bound=10)
>>> k = model.integer(5, upper_bound=55)
>>> i.maybe_equals(j)
1
>>> i.maybe_equals(k)
0

See also

equals(): A guaranteed but more expensive equality test.

reset_state(index)[source]#

Reset the state of a symbol and any successor symbols.

Parameters:

index (int) – Index of the state to reset.

Examples

This example sets two states on a symbol with two successor symbols and resets just one state.

>>> from dwave.optimization import Model
>>> model = Model()
>>> lsymbol = model.disjoint_lists_symbol(primary_set_size=5, num_disjoint_lists=2)
>>> with model.lock():
...     model.states.resize(2)
...     lsymbol.set_state(0, [[0, 4], [1, 2, 3]])
...     lsymbol.set_state(1, [[3, 4], [0, 1, 2]])
...     print(f"state 0: {lsymbol[0].state(0)} and {lsymbol[1].state(0)}")
...     print(f"state 1: {lsymbol[0].state(1)} and {lsymbol[1].state(1)}")
...     lsymbol.reset_state(0)
...     print("After reset:")
...     print(f"state 0: {lsymbol[0].state(0)} and {lsymbol[1].state(0)}")
...     print(f"state 1: {lsymbol[0].state(1)} and {lsymbol[1].state(1)}")
state 0: [0. 4.] and [1. 2. 3.]
state 1: [3. 4.] and [0. 1. 2.]
After reset:
state 0: [0. 1. 2. 3. 4.] and []
state 1: [3. 4.] and [0. 1. 2.]

See also

has_state()

shares_memory(other)[source]#

Determine if two symbols share memory.

Parameters:

other (Symbol) – Another symbol.

Returns:

True if the two symbols share memory.

Return type:

bool

See also

id()

state_size()[source]#

Return an estimated size, in bytes, of a symbol’s state.

The number of bytes returned by this method is only an estimate. Some symbols hold additional information that is not accounted for.

For most symbols, which are arrays, this method is subclassed by the ArraySymbol class’s state_size() method.

Returns:

Estimated size in bytes.

Return type:

int

See also

ArraySymbol.state_size() An estimate of the size of an array symbol’s state.

Model.state_size() An estimate of the size of a model’s state.

topological_index()[source]#

Return the topological index of the symbol.

Returns:

Value of the symbol’s topological index if the model is topologically sorted; otherwise None.

Return type:

int or None

Examples

>>> from dwave.optimization import Model
>>> model = Model()
>>> c1 = model.constant([5])
>>> c1.topological_index() is None
True
>>> with model.lock():
...     print(c1.topological_index() is None)
False

ArraySymbol#

Most mathematical symbols inherit from the ArraySymbol class and therefore inherit its methods.

class ArraySymbol[source]#

Bases: Symbol

Base class for symbols that can be interpreted as an array.

all(*, axis=None, initial=<no value>)[source]#

Create a symbol that tests whether all array elements evaluate to True.

Parameters:
  • axis (int or tuple[int, ...], optional, default=None) –

    Axis or axes along which the operation is performed. If unspecified, reduction is performed over all dimensions. If tuple[int, ...], reduction is performed along the specified axes.

    Added in version 0.6.8.

  • initial (float or None, optional) –

    This argument is ignored.

    Added in version 0.6.8.

Returns:

A successor symbol that returns True if all elements of the predecessor symbol are True.

Return type:

All

Examples

This example tests the columns of a \(2 \times 3\) array.

>>> from dwave.optimization import Model
>>> model = Model()
>>> x = model.binary((2, 3))
>>> all_x = x.all(axis=0)
>>> with model.lock():
...     model.states.resize(1)
...     x.set_state(0, [[True, False, True], [True, True, False]])
...     print(all_x.state())
[1. 0. 0.]

See also

any(*, axis=None, initial=False)[source]#

Create a symbol that tests whether any array element evaluates to True.

Parameters:
  • axis (int or tuple[int, ...], optional, default=None) –

    Axis or axes along which the operation is performed. If unspecified, reduction is performed over all dimensions. If tuple[int, ...], reduction is performed along the specified axes.

    Added in version 0.6.8.

  • initial (float or None, optional) –

    This argument is ignored.

    Added in version 0.6.8.

Returns:

A successor symbol that returns True when any element of the predecessor symbol is True.

Return type:

Any

Added in version 0.4.1.

Examples

This example tests the rows of a \(2 \times 3\) array.

>>> from dwave.optimization import Model
>>> model = Model()
>>> x = model.binary((2, 3))
>>> any_x = x.any(axis=1)
>>> with model.lock():
...     model.states.resize(1)
...     x.set_state(0, [[False, False, False], [True, False, False]])
...     print(any_x.state())
[0. 1.]

See also

copy()[source]#

Create a duplicating symbol.

Returns:

A successor symbol that maintains an identical copy of the values of the predecessor symbol, using contiguous memory for performance.

Return type:

Copy

Added in version 0.5.1.

Examples

>>> from dwave.optimization import Model
>>> model = Model()
>>> x = model.binary((2, 2))
>>> y = x.copy()
>>> with model.lock():
...     model.states.resize(1)
...     x.set_state(0, [[False, False], [True, False]])
...     print((y.state() == x.state()).all())
True

See also

flatten()[source]#

Create a symbol with the array reshaped to one dimension.

Returns:

A successor symbol that is equivalent to symbol.reshape(-1), with the predecessor symbol’s array collapsed into one dimension.

Return type:

Reshape

Added in version 0.5.1.

Examples

>>> from dwave.optimization import Model
>>> model = Model()
>>> x = model.binary((2, 2))
>>> y = x.flatten()
>>> with model.lock():
...     model.states.resize(1)
...     x.set_state(0, [[False, False], [True, False]])
...     print(x.state()[1,0] == y.state()[2] == True)
True

See also

info()[source]#

Return information about the values and size of the symbol.

Symbols might need information about their predecessor(s) to determine whether they define a valid operation. For example, a Divide symbol does not permit a denominator with zero in its possible values.

Returns:

A dataclass() object with the following fields:

  • min: Lower bound (inclusive) on the array values.

  • max: Upper bound (inclusive) on the array values.

  • integral: Whether or not the array values are always integral.

  • size: Size of the array, as one of the following values:

    • Integer if the array has a fixed size.

    • dataclass() object if the array has a dynamic size. This object has the following fields:

      • multiplier, symbol, and offset: Size of the array is \(multiplier \times \text{(size of } symbol \text{)} + offset\). If the size of the array symbol is not a linear function of another symbol, the symbol field is self.

      • min: Lower bound (inclusive) on the array size or None if the bound is uknown.

      • max: Upper bound (inclusive) on the array size or None if the bound is unknown.

Return type:

dataclass()

Added in version 0.6.8.

Examples

For a Constant symbol, min, max, integral, and size are determined by the array.

>>> import numpy as np
>>> from dwave.optimization import Model
...
>>> model = Model()
>>> c = model.constant(np.linspace(0, 4.5, num=10))
>>> c.info()
ArrayInfo(min=0.0, max=4.5, integral=False, size=10)

Because a SetVariable symbol is dynamic, its size is not expressed as an integer. And because its size is not derived from another symbol, its size is derived from itself.

>>> s = model.set(10)
>>> s.info()
ArrayInfo(min=0.0, max=9.0, integral=True, size=...)
>>> sizeinfo = s.info().size
>>> sizeinfo.multiplier
Fraction(1, 1)
>>> sizeinfo.symbol.id() == s.id()
True
>>> sizeinfo.offset
Fraction(0, 1)
>>> sizeinfo.min
0
>>> sizeinfo.max
10

If a constant array is indexed from a set, that creates another dynamic array with size derived from the set.

>>> b = c[s]
>>> b.info()
ArrayInfo(min=0.0, max=4.5, integral=False, size=...)
>>> sizeinfo = b.info().size
>>> sizeinfo.multiplier
Fraction(1, 1)
>>> sizeinfo.symbol.id() == s.id()  # size is defined by the set
True
>>> sizeinfo.offset
Fraction(0, 1)
>>> sizeinfo.min
0
>>> sizeinfo.max
10

Added in version 0.6.8.

max(*, axis=None, initial=<no value>)[source]#

Create a symbol that returns the maximum value of the array.

Parameters:
  • axis (int or tuple[int, ...], optional, default=None) –

    Axis or axes along which the operation is performed. If unspecified, reduction is performed over all dimensions. If tuple[int, ...], reduction is performed along the specified axes.

    Added in version 0.6.8.

  • initial (float or None, optional) –

    Starting value for the reduction. If unspecified, the first element of the reduction is used.

    Added in version 0.6.4.

Returns:

A successor symbol that returns the maximum value among elements of the predecessor symbol.

Return type:

Max

Examples

This example creates a symbol that returns the maximum values in columns of a \(2 \times 3\) array, with the initial argument set to zero to prevent the return of negative values.

>>> from dwave.optimization.model import Model
>>> model = Model()
>>> i = model.integer((2, 3), lower_bound=-10, upper_bound=10)
>>> i_max = i.max(axis=0, initial=0)
>>> with model.lock():
...     model.states.resize(1)
...     i.set_state(0, [[2, -4, 5], [8, -2, 7]])
...     print(i_max.state())
[8. 0. 7.]

See also

maybe_equals(other)[source]#

Compare to another symbol.

This method exists because a complete equality test can be expensive.

Parameters:

other (Symbol) – Another symbol in the model’s directed acyclic graph.

Returns:

Supported return values are the following.

  • 0—Not equal (with certainty)

  • 1—Might be equal (no guarantees); a complete equality test is necessary

  • 2—Are equal (with certainty)

Return type:

int

Examples

This example compares IntegerVariable symbols of different sizes.

>>> from dwave.optimization import Model
>>> model = Model()
>>> i = model.integer(3, lower_bound=0, upper_bound=20)
>>> j = model.integer(3, lower_bound=-10, upper_bound=10)
>>> k = model.integer(5, upper_bound=55)
>>> i.maybe_equals(j)
1
>>> i.maybe_equals(k)
0

See also

equals(): A guaranteed but more expensive equality test.

min(*, axis=None, initial=<no value>)[source]#

Create a symbol that returns the minimum value of the array.

Parameters:
  • axis (int or tuple[int, ...], optional, default=None) –

    Axis or axes along which the operation is performed. If unspecified, reduction is performed over all dimensions. If tuple[int, ...], reduction is performed along the specified axes.

    Added in version 0.6.8.

  • initial (float or None, optional) –

    Starting value for the reduction. If unspecified, the first element of the reduction is used.

    Added in version 0.6.4.

Returns:

A successor symbol that returns the minimum value among elements of the predecessor symbol.

Return type:

Min

Examples

This example creates a symbol that returns the minimum values in rows of a \(3 \times 2\) array, with the initial argument set to zero to prevent the return of positive values.

>>> from dwave.optimization.model import Model
>>> model = Model()
>>> i = model.integer((3, 2), lower_bound=-10, upper_bound=10)
>>> i_min = i.min(axis=1, initial=0)
>>> with model.lock():
...     model.states.resize(1)
...     i.set_state(0, [[2, -4], [5, 8], [-2, -7]])
...     print(i_min.state())
[-4.  0. -7.]

See also

ndim()[source]#

Return the number of dimensions for a symbol.

Returns:

Number of dimensions.

Return type:

int

Examples

>>> from dwave.optimization.model import Model
>>> model = Model()
>>> i = model.integer((3, 2), lower_bound=-10, upper_bound=10)
>>> x = model.binary(2)
>>> print(f"i: {i.ndim()}\nx: {x.ndim()}")
i: 2
x: 1

See also

prod(*, axis=None, initial=<no value>)[source]#

Create a symbol that returns the product of the array elements.

Parameters:
  • axis (int or tuple[int, ...], optional, default=None) –

    Axis or axes along which the operation is performed. If unspecified, reduction is performed over all dimensions. If tuple[int, ...], reduction is performed along the specified axes.

    Added in version 0.5.1.

  • initial (float or None, optional) –

    Starting value for the reduction. If unspecified, the first element of the reduction is used.

    Added in version 0.6.4.

Returns:

A successor symbol that returns the product of the elements of the predecessor symbol.

Return type:

Prod

Examples

This example creates a symbol that returns the product of values in columns of a \(2 \times 3\) array, with the initial argument set to two to double the returned values.

>>> from dwave.optimization.model import Model
>>> model = Model()
>>> i = model.integer((2, 3), lower_bound=-10, upper_bound=10)
>>> prod_i = i.prod(axis=0, initial=2)
>>> with model.lock():
...     model.states.resize(1)
...     i.set_state(0, [[2, -4, 5], [8, -2, 7]])
...     print(prod_i.state())
[32. 16. 70.]

See also

reshape(*shape)[source]#

Create a symbol with the array reshaped.

Parameters:

shape (int or tuple[int, ...]) – Shape of the created symbol, specified as an integer argument per dimension or a single argument formatted as a tuple or list; e.g., a.reshape((1, 2)) is equivalent to a.reshape(1, 2). One dimension can be \(-1\), in which case its size is inferred from the other dimensions. For dynamically sized array symbols, the first dimension must be specified as \(-1\) and the remaining dimensions must be even divisions or multiplications of the dimensions of the predecessor array symbol, as shown in the examples below.

Returns:

A successor symbol that reshapes the predecessor symbol without changing its values, except when the provided shape exactly matches the shape of the symbol, in which case the predecessor symbol is returned.

Return type:

Reshape or self

Examples

This example reshapes a 1D vector into a \(1 \times 3\) matrix.

>>> from dwave.optimization import Model
>>> model = Model()
>>> j = model.integer(3, lower_bound=-10, upper_bound=10)
>>> j.shape()
(3,)
>>> k = j.reshape((1, 3))
>>> k.shape()
(1, 3)

This example reshapes a dynamic 2D array symbol.

>>> import numpy as np
...
>>> model = Model()
>>> a = model.constant(np.ones((10, 4)))[model.set(10), :]
>>> a.shape()
(-1, 4)
>>> b = a.reshape(-1, 2, 2)  # OK because 2*2 = 4
>>> b.shape()
(-1, 2, 2)
>>> c = a.reshape(-1, 4, 1, 1)  # OK because 4*1*1 = 4
>>> c.shape()
(-1, 4, 1, 1)
>>> d = a.reshape(-1, 2)  # OK because 2 evenly divides 4
>>> d.shape()
(-1, 2)
>>> a.reshape(-1, 8)  # Fails because 8 does not evenly divide 4
Traceback (most recent call last):
ValueError: cannot reshape array of shape (-1, 4) into shape (-1, 8)

Added in version 0.5.1.

Added in version 0.6.5: Add support for reshaping dynamic array symbols.

See also

resize(shape, fill_value=None)[source]#

Create a symbol with the specified shape.

Parameters:
  • shape (tuple[int, ...]) – Shape of the successor array. Dimension values must be non-negative.

  • fill_value (int, optional, default=None) – Value to use if the successor array is larger than the predecessor array. Defaults to 0.

Returns:

A successor symbol with the specified shape.

Return type:

Resize

Examples

>>> from dwave.optimization import Model
...
>>> model = Model()
>>> s = model.set(10)  # subsets of range(10)
>>> s_2x2 = s.resize((2, 2), fill_value=-1)
...
>>> model.states.resize(1)
>>> with model.lock():
...     s.set_state(0, [0, 1, 2])
...     print(s_2x2.state(0))
[[ 0.  1.]
 [ 2. -1.]]

See also

Added in version 0.6.4.

shape()[source]#

Return the shape of the symbol.

Returns:

Dimensions of the array. A dynamic array symbol returns a \(-1\) in the first dimension.

Return type:

tuple

Examples

This example returns the shape of a newly instantiated symbol.

>>> from dwave.optimization import Model
>>> model = Model()
>>> x = model.binary(20)
>>> x.shape()
(20,)
>>> s = model.set(20)
>>> s.shape()
(-1,)

See also

size()[source]#

Return the number of elements in the symbol.

Returns:

Number of elements in the array. For dynamic symbols, returns a Size symbol.

Return type:

int or Size

Examples

This example checks the size of a \(2 \times 3\) binary symbol.

>>> from dwave.optimization import Model
>>> model = Model()
>>> x = model.binary((2, 3))
>>> x.size()
6

See also

state(index=0, *, copy=True)[source]#

Return the state of the symbol.

Parameters:
  • index (int, optional, default=0) – Index of the state.

  • copy (bool, optional) – Currently only True is supported.

Returns:

State of the symbol.

Return type:

numpy.ndarray

Examples

This example prints a symbol’s two states: initialized and uninitialized.

>>> from dwave.optimization import Model
>>> model = Model()
>>> x = model.binary((2, 3))
>>> z = x.sum()
>>> with model.lock():
...     model.states.resize(2)
...     x.set_state(0, [[0, 0, 1], [1, 0, 1]])
...     print(z.state(0))
...     print(z.state(1))
3.0
0.0

See also

has_state(), reset_state()

state_size()[source]#

Return an estimate of the size, in bytes, of the symbol’s state.

Returns:

Number of bytes needed to encode the array.

Return type:

int

Examples

This example returns the size of an IntegerVariable symbol that encodes a \(5 \times 4\) array of integers, each represented by an \(8\)-byte float. Therefore the estimated state size is \(5*4*8 = 160\) bytes.

>>> from dwave.optimization import Model
>>> model = Model()
>>> i = model.integer((5, 4))  # 5x4 array of integers
>>> i.state_size()             # 5*4*8 bytes
160

See also

Symbol.state_size() An estimate of the size of a symbol’s state.

Model.state_size() An estimate of the size of a model’s state.

strides()[source]#

Return the stride length, in bytes, for traversing a symbol.

Returns:

Number of bytes to step in each dimension when traversing a symbol.

Return type:

tuple

Examples

This example returns the stride length of an IntegerVariable symbol.

>>> from dwave.optimization import Model
>>> model = Model()
>>> i = model.integer((2, 3), upper_bound=20)
>>> i.strides()
(24, 8)

See also

strides: NumPy attribute

sum(*, axis=None, initial=<no value>)[source]#

Create a symbol that returns the sum of the array elements.

Parameters:
  • axis (int or tuple[int, ...], optional) –

    Axis or axes along which the operation is performed. If unspecified, reduction is performed over all dimensions. If tuple[int, ...], reduction is performed along the specified axes.

    Added in version 0.4.1.

  • initial (float or None, optional) –

    Starting value for the reduction. If unspecified, the first element of the reduction is used.

    Added in version 0.6.4.

Returns:

A successor symbol that returns the sum of the elements of the predecessor symbol.

Return type:

Sum

Examples

This example creates a symbol that returns the sum of values in columns of a \(2 \times 3\) array, with the initial argument set to \(-3\) to offset the returned values.

>>> from dwave.optimization.model import Model
>>> model = Model()
>>> i = model.integer((2, 3), lower_bound=-10, upper_bound=10)
>>> sum_i = i.sum(axis=0, initial=-3)
>>> with model.lock():
...     model.states.resize(1)
...     i.set_state(0, [[2, -4, 5], [8, -2, 7]])
...     print(sum_i.state())
[ 7. -9.  9.]

See also

Model Symbols#

Each operation, decision, constant, mathematical function, and flow control is modeled using a symbol. The following symbols are available for modelling.

In general, symbols should be created using the methods inherited from Symbol and ArraySymbol, and from mathematical functions, rather than by the constructors of the following classes. Some exceptions are noted below.

class ARange[source]#

Bases: ArraySymbol

Evenly spaced integer values within an interval.

See also

arange(): Instantiation and usage of this symbol.

Added in version 0.5.2.

class Absolute(x)[source]#

Bases: _UnaryOpSymbol

Absolute value element-wise on a symbol.

See also

absolute(): Instantiation and usage of this symbol.

class AccumulateZip[source]#

Bases: ArraySymbol

Accumulates element-wise operations over operand symbols.

Note

This symbol is used by direct instantiation, as shown in the example below.

Performs an element-wise accumulate operation, as specified by a Expression, along one or more array operands. For each output index, the operation inputs one value from each array symbol and the result of the previous operation, or, for the first index, the initial parameter.

This symbol expands the NumPy accumulate() function by enabling the accumulate operation to accept an arbitrary number of array inputs and “zipping” them together. For a given expression expr, predecessor array symbols A, B, C, and an initial value, init, this symbol is equivalent to the pseudocode:

r = [0] * len(A)
t = init
for args in zip(A, B, C):
    t = expr(t, *args)
    r[i] = t
return r
Parameters:
  • expression (Expression) – An operation to accumulate, specified as an expression. Its first argument takes the value of the initial parameter for index zero of its element-wise operation and then, for the remaining array elements, the output of the previous index. The expression’s next arguments are assigned to the symbols specified by the operands parameter.

  • operands (tuple[Symbol, …]) – Operands to the accumulate operation as an iterable of 1D-array symbols. There should be one fewer operands than arguments of the expression.

  • initial (float, optional) – Start value of the accumulate operation. Used to set the first argument of the expression on the very first iteration (index zero).

Examples

This example directly adds an AccumulateZip symbol to a model that calculates the cumulative value of the expression \(-v_0*(v_1 + v_2)\), where, for each iteration, \(v_1, v_2\) are sequential elements of two IntegerVariable symbols and \(v_0\) is the result from the previous elements or, for the first elements, defined by the configured initial value.

For example, for inputs \(v_1, v_2 = [1, 1, 0, 1, 1], [0, 0, 2, 2, 2]\) and an initial value, \(v_0[0]\) of 2, the first element of the AccumulateZip symbol is \(-2 * (1 + 0) = -2\), the 2nd is therefore \(-(-2) * (1 + 0) = 2\), the 3rd is \(-2 * (0 + 2) = -4\), etc.

>>> from dwave.optimization import expression, Model
>>> from dwave.optimization.symbols import AccumulateZip
...
>>> model = Model()
>>> i1 = model.integer(5, lower_bound=-10, upper_bound=15)
>>> i2 = model.integer(5, upper_bound=10)
>>> j = AccumulateZip(expression(lambda v0, v1, v2: -v0*(v1 + v2)), (i1, i2), initial=2)
>>> with model.lock():
...     model.states.resize(1)
...     i1.set_state(0,[1, 1, 0, 1, 1])
...     i2.set_state(0, [0, 0, 2, 2, 2])
...     print(j.state(0))
[ -2.   2.  -4.  12. -36.]

See also

accumulate(): NumPy function

Added in version 0.6.4.

class Add(lhs, rhs)[source]#

Bases: _BinaryOpSymbol

Addition element-wise of two symbols.

See also

add(): Instantiation and usage of this symbol.

NaryAdd

Divide, Modulus, Multiply, SafeDivide, Subtract

class AdvancedIndexing[source]#

Bases: ArraySymbol

Advanced indexing.

This symbol is instantiated by operations similar to those of NumPy’s advanced indexing, such as in the following example that selects row zero and column zero of an array symbol, not together (\(A[i,j]\)) but separately (\(A[[i],[j]]\)):

>>> from dwave.optimization import Model
>>> model = Model()
>>> a = model.constant([[1, 2], [3, 4]])
>>> print(type(a[0, 0]))
<class 'dwave.optimization.symbols.indexing.BasicIndexing'>
>>> print(type(a[[0], [0]]))
<class 'dwave.optimization.symbols.indexing.AdvancedIndexing'>
class All(array, *, axis=None, initial=<no value>)[source]#

Bases: _ReduceSymbol

Tests whether all elements evaluate to True.

See also

all(): Instantiation and usage of this symbol.

Any

class And(lhs, rhs)[source]#

Bases: _BinaryOpSymbol

Boolean AND element-wise between two symbols.

See also

logical_and(): Instantiation and usage of this symbol.

Logical, Not, Or, Xor

class Any(array, *, axis=None, initial=<no value>)[source]#

Bases: _ReduceSymbol

Tests whether any elements evaluate to True.

See also

any(): Instantiation and usage of this symbol.

All

class ArgSort[source]#

Bases: ArraySymbol

An ordering for a symbol’s indices that sorts its flattened array’s values.

See also

argsort(): Instantiation and usage of this symbol.

Added in version 0.6.4.

class BSpline[source]#

Bases: ArraySymbol

B-spline for a symbol.

See also

bspline(): Instantiation and usage of this symbol.

class BasicIndexing[source]#

Bases: ArraySymbol

Basic indexing.

This symbol is instantiated by operations similar to those of NumPy’s basic indexing, such as in the following example that selects row zero and column zero of an array symbol together (\(A[i,j]\)) but not separately (\(A[[i],[j]]\)) :

>>> from dwave.optimization import Model
>>> model = Model()
>>> a = model.constant([[1, 2], [3, 4]])
>>> print(type(a[0, 0]))
<class 'dwave.optimization.symbols.indexing.BasicIndexing'>
>>> print(type(a[[0], [0]]))
<class 'dwave.optimization.symbols.indexing.AdvancedIndexing'>
class BinaryVariable[source]#

Bases: ArraySymbol

Binary decision-variable symbol.

See also

binary(): Instantiation and usage of this symbol.

lower_bound()[source]#

Lower bound(s) of the symbol.

set_state(index, state)[source]#

Set the state of the symbol.

Parameters:
  • index (int) – Index of the state to set.

  • state (array-like) – Assignment of values for the state. The specified state must be binary array with the same shape as the symbol.

Examples

This example sets two states for a \(2 \times 3\)-sized binary symbol.

>>> from dwave.optimization.model import Model
>>> import numpy as np
...
>>> model = Model()
>>> x = model.binary((2, 3))
>>> model.states.resize(2)
>>> x.set_state(0, [[True, True, False], [False, True, False]])
>>> print(np.equal(x.state(0), [[True, True, False], [False, True, False]]).all())
True
>>> x.set_state(1, [[False, True, False], [False, True, False]])
>>> print(np.equal(x.state(1), [[False, True, False], [False, True, False]]).all())
True
sum_constraints()[source]#

Sum constraints of Binary symbol as a list of tuples where each tuple is of the form: ([operator], [bound]) or (axis, [operator(s)], [bound(s)]).

upper_bound()[source]#

Upper bound(s) of the symbol.

class BroadcastTo[source]#

Bases: ArraySymbol

Broadcasts an array symbol to a new shape.

See also

broadcast_to(): Instantiation and usage of this symbol.

Copy, Reshape, Resize, Roll, Transpose

Added in version 0.6.5.

state_size()[source]#

Returns zero (broadcasting symbols are effectively stateless).

class Concatenate[source]#

Bases: ArraySymbol

A symbol that concatenates one or more symbols.

See also

concatenate(): Instantiation and usage of this symbol.

hstack(), stack(), vstack()

Added in version 0.4.3.

class Constant[source]#

Bases: ArraySymbol

Constant symbol.

See also

constant(): Instantiation and usage of this symbol.

Input

maybe_equals(other)[source]#

Compare to another symbol.

This method exists because a complete equality test can be expensive.

Parameters:

other (Symbol) – Another symbol in the model’s directed acyclic graph.

Returns:

Supported return values are the following.

  • 0—Not equal (with certainty)

  • 1—Might be equal (no guarantees); a complete equality test is necessary

  • 2—Are equal (with certainty)

Return type:

int

Examples

This example compares IntegerVariable symbols of different sizes.

>>> from dwave.optimization import Model
>>> model = Model()
>>> i = model.integer(3, lower_bound=0, upper_bound=20)
>>> j = model.integer(3, lower_bound=-10, upper_bound=10)
>>> k = model.integer(5, upper_bound=55)
>>> i.maybe_equals(j)
1
>>> i.maybe_equals(k)
0

See also

equals(): A guaranteed but more expensive equality test.

state(index=0, *, copy=True)[source]#

Return the state of the symbol.

Parameters:
  • index (int) – Index of the state.

  • copy (bool) – Copy the state. Currently only True is supported.

Returns:

A copy of the state.

class Copy[source]#

Bases: ArraySymbol

A duplicating symbol.

See also

copy(): Instantiation and usage of this symbol.

BroadcastTo Reshape, Resize, Roll, Transpose

Added in version 0.5.1.

class Cos(x)[source]#

Bases: _UnaryOpSymbol

Cosine element-wise on a symbol.

See also

cos(): Instantiation and usage of this symbol.

Sin, Tanh

Added in version 0.6.5.

class DisjointBitSet[source]#

Bases: ArraySymbol

Disjoint-sets successor symbol.

See also

disjoint_bit_sets(): Instantiation and usage of this symbol.

DisjointBitSets

set_index()[source]#

Return the index for the set.

Examples

>>> from dwave.optimization.model import Model
>>> model = Model()
>>> parts_set, parts_subsets = model.disjoint_bit_sets(10, 4)
>>> parts_subsets[2].set_index()
2
class DisjointBitSets[source]#

Bases: Symbol

Disjoint-sets decision-variable symbol.

See also

disjoint_bit_sets(): Instantiation and usage of this symbol.

DisjointBitSet

DisjointLists, ListVariable, SetVariable

num_disjoint_sets()[source]#

Return the number of disjoint sets in the symbol.

Examples

>>> from dwave.optimization.model import Model
>>> model = Model()
>>> parts_set, parts_subsets = model.disjoint_bit_sets(10, 4)
>>> parts_set.num_disjoint_sets() == 4
True
set_state(index, state)[source]#

Set the state of the disjoint-sets symbol.

Parameters:
  • index (int) – Index of the state to set.

  • state (array-like) – Assignment of values for the state. The specified state must be a partition of range(primary_set_size), where the primary set size is a parameter of the instantiating disjoint_bit_sets() method, into num_disjoint_sets() partitions, encoded as a 2D num_disjoint_sets \(\times\) primary_set_size Boolean array.

Examples

>>> from dwave.optimization.model import Model
>>> model = Model()
>>> parts_set, parts_subsets = model.disjoint_bit_sets(8, 3)
>>> with model.lock():
...     model.states.resize(1)
...     parts_set.set_state(0, [[0, 1, 1, 0, 0, 0, 0, 0],
...                             [1, 0, 0, 0, 0, 1, 0, 1],
...                             [0, 0, 0, 1, 1, 0, 1, 0]])
class DisjointList[source]#

Bases: ArraySymbol

Disjoint-lists successor symbol.

See also

disjoint_lists_symbol(): Instantiation and usage of this symbol.

DisjointLists

list_index()[source]#

Return the index for the list.

Examples

>>> from dwave.optimization.model import Model
>>> model = Model()
>>> lists_symbol = model.disjoint_lists_symbol(
...     primary_set_size=5, num_disjoint_lists=3)
>>> lists_symbol[1].list_index()
1
class DisjointLists[source]#

Bases: Symbol

Disjoint-lists decision-variable symbol.

See also

disjoint_lists_symbol(): Instantiation and usage of this symbol.

DisjointList

DisjointBitSets, ListVariable, SetVariable

num_disjoint_lists()[source]#

Return the number of disjoint lists in the symbol.

Examples

>>> from dwave.optimization.model import Model
>>> model = Model()
>>> lists_symbol = model.disjoint_lists_symbol(
...     primary_set_size=5,
...     num_disjoint_lists=3)
>>> lists_symbol.num_disjoint_lists() == 3
True
primary_set_size()[source]#

Return the total number of elements in the partitioned lists.

set_state(index, state)[source]#

Set the state of the disjoint-lists symbol.

Parameters:
  • index (int) – Index of the state to set

  • state (list[list, ...]) – Assignment of values for the state. The specified state must be a partition of range(primary_set_size) into num_disjoint_lists() partitions as a list of lists.

Examples

This example sets the state of a disjoint-lists symbol. You can inspect the state of each list individually.

>>> from dwave.optimization.model import Model
>>> model = Model()
>>> lists_symbol = model.disjoint_lists_symbol(
...     primary_set_size=5,
...     num_disjoint_lists=3
... )
>>> with model.lock():
...     model.states.resize(1)
...     lists_symbol.set_state(0, [[0, 1, 2, 3], [4], []])
...     for index, disjoint_list in enumerate(lists_symbol):
...         print(f"DisjointList {index}:")
...         print(disjoint_list.state(0))
DisjointList 0:
[0. 1. 2. 3.]
DisjointList 1:
[4.]
DisjointList 2:
[]
class Divide(lhs, rhs)[source]#

Bases: _BinaryOpSymbol

Division element-wise between two symbols.

See also

divide(): Instantiation and usage of this symbol.

Add, Modulus, Multiply, SafeDivide, Subtract

class Equal(lhs, rhs)[source]#

Bases: _BinaryOpSymbol

Equality comparison element-wise between two symbols.

See also

equal(): Instantiation and usage of this symbol.

LessEqual

class Exp(x)[source]#

Bases: _UnaryOpSymbol

Natural (base-e) exponential element-wise on a symbol.

See also

exp(): Instantiation and usage of this symbol.

Expit, Log, SoftMax

Added in version 0.6.2.

class Expit(x)[source]#

Bases: _UnaryOpSymbol

Logistic sigmoid (expit) element-wise on a symbol.

See also

expit(): Instantiation and usage of this symbol.

Exp, Log, SoftMax

Added in version 0.5.2.

class Extract[source]#

Bases: ArraySymbol

Elements chosen conditionally from two array symbols.

See also

where(): Instantiation and usage of this symbol.

IsIn, Put, Where

class Input[source]#

Bases: ArraySymbol

An input symbol that acts as a placeholder in a model.

See also

input(): Instantiation and usage of this symbol.

Constant

integral()[source]#

Returns True if the symbol always returns integers.

lower_bound()[source]#

Lowest value allowed in the state.

set_state(index, state)[source]#

Set the state of the symbol.

Parameters:
  • index (int) – Index of the state to set.

  • state (array-like) – Assignment of values for the state. The specified state must have the same shape as the symbol.

Examples

>>> from dwave.optimization.model import Model
>>> model = Model()
>>> y = model.input(shape=(2, 3), upper_bound=10, integral=False)
>>> z = y.max()
>>> with model.lock():
...     model.states.resize(1)
...     y.set_state(0, [[1.5, 2, 9], [-12, 4, 10]])
...     print(z.state(0))
10.0
upper_bound()[source]#

Largest value allowed in the state.

class IntegerVariable[source]#

Bases: ArraySymbol

Integer decision-variable symbol.

See also

integer(): Instantiation and usage of this symbol.

lower_bound()[source]#

Lower bound(s) of the symbol.

set_state(index, state)[source]#

Set the state of the integer symbol.

Parameters:
  • index (int) – Index of the state to set.

  • state (array-like) – Assignment of values for the state. The specified state must have the same shape as the symbol.

Examples

This example successfully sets one state for a \(2 \times 2\)-sized integer symbol.

>>> from dwave.optimization.model import Model
>>> import numpy as np
...
>>> model = Model()
>>> x = model.integer((2, 2), lower_bound=2, upper_bound=[[3,4], [2, 5]])
>>> model.states.resize(1)
>>> x.set_state(0, [[3, 4], [2, 3]])
>>> print(np.equal(x.state(0), [[3, 4], [2, 3]]).all())
True
sum_constraints()[source]#

Sum constraints of Integer symbol as a list of tuples where each tuple is of the form: ([operator], [bound]) or (axis, [operator(s)], [bound(s)]).

upper_bound()[source]#

Upper bound(s) of the symbol.

class IsIn[source]#

Bases: ArraySymbol

Tests which values of one symbol are in another symbol.

See also

isin(): Instantiation and usage of this symbol.

Extract, Put, Where

Added in version 0.6.8.

class LessEqual(lhs, rhs)[source]#

Bases: _BinaryOpSymbol

Smaller-or-equal comparison element-wise between two symbols.

See also

less_equal(): Instantiation and usage of this symbol.

Equal

class LinearProgram[source]#

Bases: Symbol

Solves a linear program (LP) defined by the predecessors.

See also

linprog(): Instantiation and usage of this symbol.

LinearProgramFeasible, LinearProgramObjectiveValue, LinearProgramSolution

Examples

>>> from dwave.optimization import linprog, Model
...
>>> model = Model()
>>> c = model.constant([-1, -2])
>>> A_ub = model.constant([[1, 1]])
>>> b_ub = model.constant([1])
>>> res = linprog(c, A_ub=A_ub, b_ub=b_ub)
>>> _ = model.add_constraint(res.success)  # tell the model you want feasible solutions
...
>>> with model.lock():
...     model.states.resize(1)
...     print(res.lp.feasible(), res.lp.objective_value(), res.lp.state())
True -2.0 [0. 1.]

Added in version 0.6.0.

feasible(index=0)[source]#

Return True if the indexed state is a feasible solution.

This method returns a boolean value. To use feasibility in the model, use the LinearProgramFeasible symbol.

Parameters:

index (int) – Index of the state to test.

Examples

See the example in the LinearProgram class.

Added in version 0.6.12.

objective_value(index=0)[source]#

Return the objective value for the indexed state.

If the state is not a feasible solution, the objective value is not meaningful.

This method returns a numeric value. To use the objective value in the model, use the LinearProgramObjectiveValue class.

Parameters:

index (int) – Index of the returned state.

Examples

See the example in the LinearProgram class.

Added in version 0.6.12.

state(index=0)[source]#

Return the indexed state’s values.

This method returns an array. To use the state in the model, use the LinearProgramSolution class.

Parameters:

index (int) – Index of the returned state.

Examples

See the example in the LinearProgram class.

Added in version 0.6.0.

class LinearProgramFeasible[source]#

Bases: ArraySymbol

Returns True if the predecessor symbol’s indexed state is a feasible solution.

See also

linprog(): Instantiation and usage of this symbol.

LinearProgram, LinearProgramObjectiveValue, LinearProgramSolution

Added in version 0.6.0.

class LinearProgramObjectiveValue[source]#

Bases: ArraySymbol

Returns the objective value for the predecessor symbol’s indexed state.

See also

linprog(): Instantiation and usage of this symbol.

LinearProgram, LinearProgramFeasible, LinearProgramSolution

Added in version 0.6.0.

class LinearProgramSolution[source]#

Bases: ArraySymbol

Returns the current solution of the predecessor symbol as an array.

See also

linprog(): Instantiation and usage of this symbol.

LinearProgram, LinearProgramFeasible, LinearProgramObjectiveValue

Added in version 0.6.0.

class ListVariable[source]#

Bases: ArraySymbol

List decision-variable symbol.

The variable’s possible states are the ordered subsets of range(n).

See also

list(): Instantiation and usage of this symbol.

DisjointBitSets, DisjointLists, SetVariable

set_state(index, values)[source]#

Set the state of the symbol.

Parameters:
  • index (int) – Index of the state to set.

  • values (array-like) – Assignment of values for the state. The specified values must be a permuation of range(n) where n is the size of the list.

Examples

>>> from dwave.optimization.model import Model
>>> i = model.integer(5)
>>> with model.lock():
...     model.states.resize(2)
...     i.set_state(0, [0, 2, 1, 3, 4])
...     i.set_state(1, [4, 3, 0, 1, 2])
class Log(x)[source]#

Bases: _UnaryOpSymbol

Natural logarithm (log) element-wise on a symbol.

See also

log(): Instantiation and usage of this symbol.

Exp, Expit, SoftMax

Added in version 0.5.2.

class Logical(x)[source]#

Bases: _UnaryOpSymbol

Logical truth value element-wise on a symbol.

See also

logical(): Instantiation and usage of this symbol.

And, Not, Or, Xor

class MatrixMultiply[source]#

Bases: ArraySymbol

Matrix product of two array symbols.

See also

matmul(): Instantiation and usage of this symbol.

Multiply, Prod

Added in version 0.6.10.

static implementation()[source]#

Return the matrix multiplication implementation.

Either “blas” (BLAS) or “fallback”.

class Max(array, *, axis=None, initial=<no value>)[source]#

Bases: _ReduceSymbol

Maximum value in the elements of a symbol.

See also

max(): Instantiation and usage of this symbol.

Maximum

Min, Prod, Sum

class Maximum(lhs, rhs)[source]#

Bases: _BinaryOpSymbol

Maximum values in an element-wise comparison of two symbols.

See also

maximum(): Instantiation and usage of this symbol.

Max, NaryMaximum

class Mean[source]#

Bases: ArraySymbol

Mean value of the elements of a symbol.

See also

mean(): Instantiation and usage of this symbol.

Added in version 0.6.4.

class Min(array, *, axis=None, initial=<no value>)[source]#

Bases: _ReduceSymbol

Minimum value in the elements of a symbol.

See also

min(): Instantiation and usage of this symbol.

Minimum

Max, Prod, Sum

class Minimum(lhs, rhs)[source]#

Bases: _BinaryOpSymbol

Minimum values in an element-wise comparison of two symbols.

See also

minimum(): Instantiation and usage of this symbol.

Min, NaryMinimum

class Modulus(lhs, rhs)[source]#

Bases: _BinaryOpSymbol

Modulus element-wise between two symbols.

See also

mod(): Instantiation and usage of this symbol.

Add, Divide, Multiply, SafeDivide, Subtract

class Multiply(lhs, rhs)[source]#

Bases: _BinaryOpSymbol

Multiplication element-wise between two symbols.

See also

multiply(): Instantiation and usage of this symbol.

MatrixMultiply, Prod

Add, Divide, Modulus, SafeDivide, Subtract

NaryMultiply

class NaryAdd[source]#

Bases: ArraySymbol

Addition element-wise of N symbols.

See also

add(): Instantiation and usage of this symbol.

Add

class NaryMaximum[source]#

Bases: ArraySymbol

Maximum values in an element-wise comparison of N symbols.

See also

maximum(): Instantiation and usage of this symbol.

Maximum

class NaryMinimum[source]#

Bases: ArraySymbol

Minimum values in an element-wise comparison of N symbols.

See also

minimum(): Instantiation and usage of this symbol.

Minimum

class NaryMultiply[source]#

Bases: ArraySymbol

Multiplication element-wise between N symbols.

See also

multiply(): Instantiation and usage of this symbol.

Multiply

class Negative(x)[source]#

Bases: _UnaryOpSymbol

Numerical negative element-wise on a symbol.

This symbol is instantiated by the minus operation, such as in the following example.

Examples

>>> from dwave.optimization import Model
>>> i = model.integer(3)
>>> j = - i
>>> type(j)
<class 'dwave.optimization.symbols.unaryop.Negative'>
class Not(x)[source]#

Bases: _UnaryOpSymbol

Logical negation element-wise on a symbol.

See also

logical_not(): Instantiation and usage of this symbol.

And, Logical, Or, Xor

class Or(lhs, rhs)[source]#

Bases: _BinaryOpSymbol

Boolean OR element-wise between two symbols.

See also

logical_or(): Instantiation and usage of this symbol.

And, Logical, Not, Xor

PartialProd[source]#

alias of Prod

PartialSum[source]#

alias of Sum

class Permutation[source]#

Bases: ArraySymbol

Permutation of the elements of a symbol.

This symbol is instantiated by operations similar to those of NumPy’s advanced indexing, such as in the following example.

Examples

>>> from dwave.optimization import Model
>>> model = Model()
>>> c = model.constant([[1, 2, 3], [4, 5, 6], [7, 8, 9]])
>>> x = model.list(3)
>>> d = c[x, :][: ,x]
>>> print(type(d))
<class 'dwave.optimization.symbols.indexing.Permutation'>
class Prod(array, *, axis=None, initial=<no value>)[source]#

Bases: _ReduceSymbol

Product of the elements of a symbol.

See also

prod(): Instantiation and usage of this symbol.

MatrixMultiply, Multiply

Max, Min, Sum

class Put[source]#

Bases: ArraySymbol

Replaces the specified elements in a symbol with given values.

See also

put(): Instantiation and usage of this symbol.

Extract, IsIn, Where

Added in version 0.4.4.

class QuadraticModel[source]#

Bases: ArraySymbol

A quadratic model derived from a predecessor symbol and quadratic interactions.

See also

quadratic_model(): Instantiation and usage of this symbol.

get_linear(v)[source]#

Return the linear bias of a variable.

Parameters:

v (int) – A variable (or node) of the model.

Returns:

Linear bias.

Return type:

float

get_quadratic(u, v)[source]#

Return the quadratic interaction between two variables.

Parameters:
  • u (int) – A variable (or node) of the model.

  • v (int) – A variable (or node) of the model.

Returns:

Quadratic bias. Returns 0 if not present.

Return type:

float

Examples

>>> from dwave.optimization.model import Model
>>> model = Model()
>>> x = model.binary(3)
>>> Q = {(0, 0): 0, (0, 1): 1, (0, 2): 2, (1, 1): 1, (1, 2): 3, (2, 2): 2}
>>> qm = model.quadratic_model(x, Q)
>>> qm.get_quadratic(1, 2)
3.0
num_interactions()[source]#

Number of quadratic interactions in the quadratic model.

num_variables()[source]#

Number of variables in the quadratic model.

class Reshape[source]#

Bases: ArraySymbol

Reshaped symbol.

See also

reshape(): Instantiation and usage of this symbol.

BroadcastTo, Copy, Reshape, Resize, Roll, Transpose

Added in version 0.5.1.

class Resize[source]#

Bases: ArraySymbol

Resize symbol.

See also

resize(): Instantiation and usage of this symbol.

resize(): ArraySymbol method.

BroadcastTo, Copy, Reshape, Roll, Transpose

Added in version 0.6.4.

class Rint(x)[source]#

Bases: _UnaryOpSymbol

Rounds the values of a symbol to the nearest integer.

See also

  • rint(): Instantiation and usage of this symbol.

class Roll[source]#

Bases: ArraySymbol

Roll elements of a symbol along an axis.

See also

roll(): Instantiation and usage of this symbol.

BroadcastTo, Copy, Reshape, Resize, Transpose

Added in version 0.6.9.

maybe_equals(other)[source]#

Compare to another symbol.

This method exists because a complete equality test can be expensive.

Parameters:

other (Symbol) – Another symbol in the model’s directed acyclic graph.

Returns:

Supported return values are the following.

  • 0—Not equal (with certainty)

  • 1—Might be equal (no guarantees); a complete equality test is necessary

  • 2—Are equal (with certainty)

Return type:

int

Examples

This example compares IntegerVariable symbols of different sizes.

>>> from dwave.optimization import Model
>>> model = Model()
>>> i = model.integer(3, lower_bound=0, upper_bound=20)
>>> j = model.integer(3, lower_bound=-10, upper_bound=10)
>>> k = model.integer(5, upper_bound=55)
>>> i.maybe_equals(j)
1
>>> i.maybe_equals(k)
0

See also

equals(): A guaranteed but more expensive equality test.

class SafeDivide(lhs, rhs)[source]#

Bases: _BinaryOpSymbol

Safe division element-wise between two symbols.

See also

safe_divide(): Instantiation and usage of this symbol.

Add, Divide, Modulus, Multiply, Subtract

Added in version 0.6.2.

class SetVariable[source]#

Bases: ArraySymbol

Set decision-variable symbol.

A set variable’s possible states are the subsets of range(n).

See also

set(): Instantiation and usage of this symbol.

DisjointBitSets, DisjointLists, ListVariable

set_state(index, values)[source]#

Set the state of the symbol.

index (int):

Index of the state to set.

values (array-like):

Assignment of values for the state. The given state must be a subset of range(n) where n is the size of the set.

Examples

>>> from dwave.optimization.model import Model
>>> model = Model()
>>> s = model.set(10, min_size=2, max_size=5)
>>> with model.lock():
...     model.states.resize(2)
...     s.set_state(0, {0, 2, 1})
...     s.set_state(1, {2, 3, 4, 7, 9})
class Sin(x)[source]#

Bases: _UnaryOpSymbol

Sine element-wise on a symbol.

See also

sin(): Instantiation and usage of this symbol.

Cos, Tanh

Added in version 0.6.5.

class Size[source]#

Bases: ArraySymbol

Size of the symbol.

See also

size(): Instantiation and usage of this symbol.

class SoftMax[source]#

Bases: ArraySymbol

Softmax of a symbol.

See also

softmax(): Instantiation and usage of this symbol.

Exp, Expit, Log

Added in version 0.6.5.

class Square(x)[source]#

Bases: _UnaryOpSymbol

Squares element-wise of a symbol.

This symbol is instantiated by a power-of-two operation, such as in the following example.

Examples

>>> from dwave.optimization import Model
>>> model = Model()
>>> i = model.integer(30)
>>> j = i**2
>>> print(type(j))
<class 'dwave.optimization.symbols.unaryop.Square'>

See also

SquareRoot

class SquareRoot(x)[source]#

Bases: _UnaryOpSymbol

Square root of a symbol.

See also

sqrt(): Instantiation and usage of this symbol.

Square

class Subtract(lhs, rhs)[source]#

Bases: _BinaryOpSymbol

Subtraction element-wise of two symbols.

See also

subtract(): Instantiation and usage of this symbol.

Add, Divide, Modulus, Multiply, SafeDivide,

class Sum(array, *, axis=None, initial=<no value>)[source]#

Bases: _ReduceSymbol

Sum of the elements of a symbol.

See also

sum(): Instantiation and usage of this symbol.

Max, Min, Prod

class Tanh(x)[source]#

Bases: _UnaryOpSymbol

Tanh element-wise on a symbol.

See also

tanh(): Instantiation and usage of this symbol.

Cos, Sin

Added in version 0.6.11.

class Transpose[source]#

Bases: ArraySymbol

Tranpose symbol.

See also

transpose(): Instantiation and usage of this symbol.

BroadcastTo, Copy, Reshape, Resize Roll

Added in version 0.6.8.

class Where[source]#

Bases: ArraySymbol

Return elements chosen from x or y depending on condition.

See also

where(): Instantiation and usage of this symbol.

Extract, IsIn, Put

class Xor(lhs, rhs)[source]#

Bases: _BinaryOpSymbol

Boolean XOR element-wise between two symbols.

See also

logical_xor(): Instantiation and usage of this symbol.

And, Logical, Not, Or

Added in version 0.4.1.