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:
Note that comparing symbols across models is expensive.
Examples
This example creates two symbols that are the sum of the same two
IntegerVariablesymbols 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:
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
- 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 asid(symbol)!- Returns:
Identity of the underlying node.
- Return type:
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
shares_memory():a.shares_memory(b)is equivalent toa.id() == b.id().equals():a.equals(b)returnsTrueifa.id() == b.id(); the inverse is not necessarily true.
- 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
Fig. 257 Visualization of the model as a directed acyclic graph. See the
to_networkx()function for information on visualizing models.#See also
- 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
Fig. 258 Visualization of the model as a directed acyclic graph. See the
to_networkx()function for information on visualizing models.#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 necessary2—Are equal (with certainty)
- Return type:
Examples
This example compares
IntegerVariablesymbols 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
Determine if two symbols share memory.
- Parameters:
other (
Symbol) – Another symbol.- Returns:
True if the two symbols share memory.
- Return type:
See also
- 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
ArraySymbolclass’sstate_size()method.- Returns:
Estimated size in bytes.
- Return type:
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:
SymbolBase 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:
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.]
- 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:
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.]
- 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:
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
- 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:
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
- 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
Dividesymbol 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, andoffset: 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, thesymbolfield isself.min: Lower bound (inclusive) on the array size orNoneif the bound is uknown.max: Upper bound (inclusive) on the array size orNoneif the bound is unknown.
- Return type:
Added in version 0.6.8.
Examples
For a
Constantsymbol,min,max,integral, andsizeare 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
SetVariablesymbol 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:
Examples
This example creates a symbol that returns the maximum values in columns of a \(2 \times 3\) array, with the
initialargument 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.]
- 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 necessary2—Are equal (with certainty)
- Return type:
Examples
This example compares
IntegerVariablesymbols 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:
Examples
This example creates a symbol that returns the minimum values in rows of a \(3 \times 2\) array, with the
initialargument 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.]
- ndim()[source]#
Return the number of dimensions for a symbol.
- Returns:
Number of dimensions.
- Return type:
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
- 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:
Examples
This example creates a symbol that returns the product of values in columns of a \(2 \times 3\) array, with the
initialargument 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.]
- 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 toa.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:
Reshapeorself
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.
- resize(shape, fill_value=None)[source]#
Create a symbol with the specified shape.
- Parameters:
- Returns:
A successor symbol with the specified shape.
- Return type:
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.]]
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:
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,)
- size()[source]#
Return the number of elements in the symbol.
- Returns:
Number of elements in the array. For dynamic symbols, returns a
Sizesymbol.- 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
- state(index=0, *, copy=True)[source]#
Return the state of the symbol.
- Parameters:
- Returns:
State of the symbol.
- Return type:
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:
Examples
This example returns the size of an
IntegerVariablesymbol 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:
Examples
This example returns the stride length of an
IntegerVariablesymbol.>>> from dwave.optimization import Model >>> model = Model() >>> i = model.integer((2, 3), upper_bound=20) >>> i.strides() (24, 8)
- 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:
Examples
This example creates a symbol that returns the sum of values in columns of a \(2 \times 3\) array, with the
initialargument 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.]
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:
ArraySymbolEvenly 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:
_UnaryOpSymbolAbsolute value element-wise on a symbol.
See also
absolute(): Instantiation and usage of this symbol.
- class AccumulateZip[source]#
Bases:
ArraySymbolAccumulates 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, theinitialparameter.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 expressionexpr, predecessor array symbolsA,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 theinitialparameter 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 theoperandsparameter.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
AccumulateZipsymbol 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 twoIntegerVariablesymbols and \(v_0\) is the result from the previous elements or, for the first elements, defined by the configuredinitialvalue.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
AccumulateZipsymbol 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 functionAdded in version 0.6.4.
- class AdvancedIndexing[source]#
Bases:
ArraySymbolAdvanced 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'>
See also
- class All(array, *, axis=None, initial=<no value>)[source]#
Bases:
_ReduceSymbolTests whether all elements evaluate to True.
- class Any(array, *, axis=None, initial=<no value>)[source]#
Bases:
_ReduceSymbolTests whether any elements evaluate to True.
- class ArgSort[source]#
Bases:
ArraySymbolAn 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:
ArraySymbolB-spline for a symbol.
See also
bspline(): Instantiation and usage of this symbol.
- class BasicIndexing[source]#
Bases:
ArraySymbolBasic 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'>
See also
- class BinaryVariable[source]#
Bases:
ArraySymbolBinary decision-variable symbol.
See also
binary(): Instantiation and usage of this 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
- class BroadcastTo[source]#
Bases:
ArraySymbolBroadcasts an array symbol to a new shape.
See also
broadcast_to(): Instantiation and usage of this symbol.Added in version 0.6.5.
- class Concatenate[source]#
Bases:
ArraySymbolA symbol that concatenates one or more symbols.
Added in version 0.4.3.
- class Constant[source]#
Bases:
ArraySymbolConstant symbol.
- 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 necessary2—Are equal (with certainty)
- Return type:
Examples
This example compares
IntegerVariablesymbols 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 Copy[source]#
Bases:
ArraySymbolA duplicating symbol.
See also
copy(): Instantiation and usage of this symbol.Added in version 0.5.1.
- class Cos(x)[source]#
Bases:
_UnaryOpSymbolCosine element-wise on a symbol.
Added in version 0.6.5.
- class DisjointBitSet[source]#
Bases:
ArraySymbolDisjoint-sets successor symbol.
- class DisjointBitSets[source]#
Bases:
SymbolDisjoint-sets decision-variable symbol.
See also
disjoint_bit_sets(): Instantiation and usage of this symbol.- 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 instantiatingdisjoint_bit_sets()method, intonum_disjoint_sets()partitions, encoded as a 2Dnum_disjoint_sets\(\times\)primary_set_sizeBoolean 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:
ArraySymbolDisjoint-lists successor symbol.
- class DisjointLists[source]#
Bases:
SymbolDisjoint-lists decision-variable symbol.
See also
disjoint_lists_symbol(): Instantiation and usage of this symbol.- 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
- 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)intonum_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 Equal(lhs, rhs)[source]#
Bases:
_BinaryOpSymbolEquality comparison element-wise between two symbols.
- class Exp(x)[source]#
Bases:
_UnaryOpSymbolNatural (base-e) exponential element-wise on a symbol.
Added in version 0.6.2.
- class Expit(x)[source]#
Bases:
_UnaryOpSymbolLogistic sigmoid (expit) element-wise on a symbol.
Added in version 0.5.2.
- class Extract[source]#
Bases:
ArraySymbolElements chosen conditionally from two array symbols.
- class Input[source]#
Bases:
ArraySymbolAn input symbol that acts as a placeholder in a model.
- 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
- class IntegerVariable[source]#
Bases:
ArraySymbolInteger decision-variable symbol.
See also
integer(): Instantiation and usage of this 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
- class IsIn[source]#
Bases:
ArraySymbolTests which values of one symbol are in another symbol.
Added in version 0.6.8.
- class LessEqual(lhs, rhs)[source]#
Bases:
_BinaryOpSymbolSmaller-or-equal comparison element-wise between two symbols.
- class LinearProgram[source]#
Bases:
SymbolSolves a linear program (LP) defined by the predecessors.
See also
linprog(): Instantiation and usage of this symbol.LinearProgramFeasible,LinearProgramObjectiveValue,LinearProgramSolutionExamples
>>> 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
LinearProgramFeasiblesymbol.- Parameters:
index (int) – Index of the state to test.
Examples
See the example in the
LinearProgramclass.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
LinearProgramObjectiveValueclass.- Parameters:
index (int) – Index of the returned state.
Examples
See the example in the
LinearProgramclass.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
LinearProgramSolutionclass.- Parameters:
index (int) – Index of the returned state.
Examples
See the example in the
LinearProgramclass.Added in version 0.6.0.
- class LinearProgramFeasible[source]#
Bases:
ArraySymbolReturns True if the predecessor symbol’s indexed state is a feasible solution.
See also
linprog(): Instantiation and usage of this symbol.LinearProgram,LinearProgramObjectiveValue,LinearProgramSolutionAdded in version 0.6.0.
- class LinearProgramObjectiveValue[source]#
Bases:
ArraySymbolReturns the objective value for the predecessor symbol’s indexed state.
See also
linprog(): Instantiation and usage of this symbol.Added in version 0.6.0.
- class LinearProgramSolution[source]#
Bases:
ArraySymbolReturns the current solution of the predecessor symbol as an array.
See also
linprog(): Instantiation and usage of this symbol.LinearProgram,LinearProgramFeasible,LinearProgramObjectiveValueAdded in version 0.6.0.
- class ListVariable[source]#
Bases:
ArraySymbolList decision-variable symbol.
The variable’s possible states are the ordered subsets of
range(n).See also
list(): Instantiation and usage of this symbol.- 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)wherenis 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:
_UnaryOpSymbolNatural logarithm (log) element-wise on a symbol.
Added in version 0.5.2.
- class MatrixMultiply[source]#
Bases:
ArraySymbolMatrix product of two array symbols.
Added in version 0.6.10.
- class Max(array, *, axis=None, initial=<no value>)[source]#
Bases:
_ReduceSymbolMaximum value in the elements of a symbol.
- class Maximum(lhs, rhs)[source]#
Bases:
_BinaryOpSymbolMaximum values in an element-wise comparison of two symbols.
- class Mean[source]#
Bases:
ArraySymbolMean 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:
_ReduceSymbolMinimum value in the elements of a symbol.
- class Minimum(lhs, rhs)[source]#
Bases:
_BinaryOpSymbolMinimum values in an element-wise comparison of two symbols.
- class Multiply(lhs, rhs)[source]#
Bases:
_BinaryOpSymbolMultiplication element-wise between two symbols.
See also
multiply(): Instantiation and usage of this symbol.
- class NaryAdd[source]#
Bases:
ArraySymbolAddition element-wise of N symbols.
- class NaryMaximum[source]#
Bases:
ArraySymbolMaximum values in an element-wise comparison of N symbols.
- class NaryMinimum[source]#
Bases:
ArraySymbolMinimum values in an element-wise comparison of N symbols.
- class NaryMultiply[source]#
Bases:
ArraySymbolMultiplication element-wise between N symbols.
- class Negative(x)[source]#
Bases:
_UnaryOpSymbolNumerical 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 Permutation[source]#
Bases:
ArraySymbolPermutation 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'>
See also
- class Prod(array, *, axis=None, initial=<no value>)[source]#
Bases:
_ReduceSymbolProduct of the elements of a symbol.
- class Put[source]#
Bases:
ArraySymbolReplaces the specified elements in a symbol with given values.
Added in version 0.4.4.
- class QuadraticModel[source]#
Bases:
ArraySymbolA quadratic model derived from a predecessor symbol and quadratic interactions.
See also
quadratic_model(): Instantiation and usage of this symbol.- get_quadratic(u, v)[source]#
Return the quadratic interaction between two variables.
- Parameters:
- Returns:
Quadratic bias. Returns 0 if not present.
- Return type:
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
- class Reshape[source]#
Bases:
ArraySymbolReshaped symbol.
See also
reshape(): Instantiation and usage of this symbol.Added in version 0.5.1.
- class Resize[source]#
Bases:
ArraySymbolResize symbol.
Added in version 0.6.4.
- class Rint(x)[source]#
Bases:
_UnaryOpSymbolRounds the values of a symbol to the nearest integer.
See also
rint(): Instantiation and usage of this symbol.
- class Roll[source]#
Bases:
ArraySymbolRoll elements of a symbol along an axis.
See also
roll(): Instantiation and usage of this symbol.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 necessary2—Are equal (with certainty)
- Return type:
Examples
This example compares
IntegerVariablesymbols 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:
_BinaryOpSymbolSafe division element-wise between two symbols.
See also
safe_divide(): Instantiation and usage of this symbol.Added in version 0.6.2.
- class SetVariable[source]#
Bases:
ArraySymbolSet decision-variable symbol.
A set variable’s possible states are the subsets of
range(n).See also
set(): Instantiation and usage of this symbol.- 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)wherenis 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 Size[source]#
Bases:
ArraySymbolSize of the symbol.
See also
size(): Instantiation and usage of this symbol.
- class SoftMax[source]#
Bases:
ArraySymbolSoftmax of a symbol.
Added in version 0.6.5.
- class Square(x)[source]#
Bases:
_UnaryOpSymbolSquares 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
- class Subtract(lhs, rhs)[source]#
Bases:
_BinaryOpSymbolSubtraction 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:
_ReduceSymbolSum of the elements of a symbol.
- class Tanh(x)[source]#
Bases:
_UnaryOpSymbolTanh element-wise on a symbol.
Added in version 0.6.11.
- class Transpose[source]#
Bases:
ArraySymbolTranpose symbol.
See also
transpose(): Instantiation and usage of this symbol.Added in version 0.6.8.
- class Where[source]#
Bases:
ArraySymbolReturn elements chosen from x or y depending on condition.