Parent Classes
Note that the utils
module will not be imported with from qubovert import *
. You must import qubovert.utils
explicitly.
Accessed with qubovert.utils.class_name
DictArithmetic
- class qubovert.utils.DictArithmetic(*args, **kwargs)
DictArithmetic.
A class to handle dictionaries. It is the same thing as a dictionary with some methods modified.
One method is that values will always default to 0. Consider the following example:
>>> d = DictArithmetic() >>> print(d[(0, 0)]) # will print 0 >>> d[(0, 0)] += 1 >>> print(d) # will print {(0, 0): 1}
Compared to an ordinary dictionary.
>>> g = dict() >>> print(g[(0, 0)]) # will raise KeyError >>> g[(0, 0)] += 1 # will raise KeyError, since (0, 0) was never set
One method is that if we set an item to 0, it will be removed. Consider the following example:
>>> d = DictArithmetic() >>> d[(0, 0)] += 1 >>> d[(0, 0)] -= 1 >>> print(d) # will print {}
One method is that if we initialize DictArithmetic with a previous dictionary it will be reinitialized to ensure that the DictArithmetic contains no zero values. Consider the following example:
>>> d = DictArithmetic({0: 1, (1, 0): 2, (2, 0): 0}) >>> print(d) # will print {0: 1, (1, 0): 2}
We also change the update method so that it follows all the conventions.
>>> d = DictArithmetic({'a': 1, (0, 1): 2}) >>> d.update({'a': 0, (1, 1): -1}) >>> print(d) # will print {(0, 1): 2, (1, 1): -1}
We also include arithmetic, addition, subtraction, scalar division, scalar multiplication, and all those in place. For example,
>>> d = DictArithmetic({(0, 0): 1, (0, 1): -2}) >>> g = d + {(0, 0): -1} >>> print(g) # will print {(0, 1): -2} >>> g *= 4 >>> print(g) # will print {(0, 1): -8} >>> g -= {(0, 1): -8} >>> print(g) # will print {}
Adding or subtracting constants will update the () element of the dict.
>>> d = DictArithmetic() >>> d += 5 >>> print(d) {(): 5}
You can give it a name.
>>> d = DictArithmetic() >>> d.name None >>> d.name = 'd' >>> d.name 'd'
__init__.
Initialize the object. If you supply args and kwargs that represent a dictionary, they will be reinitialized to follow the conventions set in
__setitem__
.- Parameters
arguments (define a dictionary with
dict(*args, **kwargs)
.) – The dictionary will be initialized to follow all the convensions of the class.
- clear() None. Remove all items from D.
- copy()
copy.
Same as dict.copy, but we adjust the method so that it returns a DictArithmetic object, or whatever object is the subclass.
- Returns
d – Same as
self.__class__
.- Return type
DictArithmetic object, or subclass of.
- classmethod create_var(name)
create_var.
Create the variable with name
name
.- Parameters
name (hashable object allowed as a key.) – Name of the variable.
- Returns
res – The model representing the variable with type
cls
.- Return type
cls object.
Examples
>>> from qubovert.utils import DictArithmetic >>> >>> x = DictArithmetic.create_var('x') >>> x == DictArithmetic({('x',): 1}) True >>> isinstance(x, DictArithmetic) True >>> x.name 'x'
>>> from qubovert import QUSO >>> >>> z = QUSO.create_var('z') >>> print(z) {('z',): 1} >>> print(isinstance(z, QUSO)) True >>> print(z.name) 'z'
- fromkeys(value=None, /)
Create a new dictionary with keys from iterable and values set to value.
- get(key, default=None, /)
Return the value for key if key is in the dictionary, else default.
- items() a set-like object providing a view on D's items
- keys() a set-like object providing a view on D's keys
- property name
name.
Return the name of the object.
- Returns
name
- Return type
object.
Example
>>> d = DictArithmetic() >>> d.name None >>> d.name = 'd' >>> d.name 'd'
- normalize(value=1)
normalize.
Normalize the coefficients to a maximum magnitude.
- Parameters
value (float (optional, defaults to 1)) – Every coefficient value will be normalized such that the coefficient with the maximum magnitude will be +/- 1.
Examples
>>> from qubovert.utils import DictArithmetic >>> d = DictArithmetic({(0, 1): 1, (1, 2, 'x'): 4}) >>> d.normalize() >>> print(d) {(0, 1): 0.25, (1, 2, 'x'): 1}
>>> from qubovert.utils import DictArithmetic >>> d = DictArithmetic({(0, 1): 1, (1, 2, 'x'): -4}) >>> d.normalize() >>> print(d) {(0, 1): 0.25, (1, 2, 'x'): -1}
>>> from qubovert import PUBO >>> d = PUBO({(0, 1): 1, (1, 2, 'x'): 4}) >>> d.normalize() >>> print(d) {(0, 1): 0.25, (1, 2, 'x'): 1}
>>> from qubovert.utils import PUBO >>> d = PUBO({(0, 1): 1, (1, 2, 'x'): -4}) >>> d.normalize() >>> print(d) {(0, 1): 0.25, (1, 2, 'x'): -1}
- property num_terms
num_terms.
Return the number of terms in the dictionary.
- Returns
n – Number of terms in the dictionary.
- Return type
int.
- pop(k[, d]) v, remove specified key and return the corresponding value.
If key is not found, d is returned if given, otherwise KeyError is raised
- popitem()
Remove and return a (key, value) pair as a 2-tuple.
Pairs are returned in LIFO (last-in, first-out) order. Raises KeyError if the dict is empty.
- pretty_str(var_prefix='x')
pretty_str.
Return a pretty string representation of the model.
- Parameters
var_prefix (str (optional, defaults to
'x'
).) – The prefix for the variables.- Returns
res
- Return type
str.
- setdefault(key, default=None, /)
Insert key with a value of default if key is not in the dictionary.
Return the value for key if key is in the dictionary, else default.
- simplify()
simplify.
If
self
has any symbolic expressions, this will go through and simplify them. This will also make everything a float!- Returns
- Return type
None. Updates it in place.
- subgraph(nodes, connections=None)
subgraph.
Create the subgraph of
self
that only includes vertices innodes
, and external nodes are given the values inconnections
.- Parameters
nodes (set.) – Nodes of
self
to include in the subgraph.connections (dict (optional, defaults to {})) – For each node in
self
that is not innodes
, we assign a value given byconnections.get(node, 0)
.
- Returns
D – The subgraph of
self
with nodes innodes
and the values of the nodes not included given byconnections
.- Return type
same as type(self)
Notes
Any offset value included in
self
(ie {(): 1}) will be ignored, however there may be an offset in the outputD
.Examples
>>> G = DictArithmetic( >>> {(0, 1): -4, (0, 2): -1, (0,): 3, (1,): 2, (): 2} >>> ) >>> D = G.subgraph({0, 2}, {1: 5}) >>> D {(0,): -17, (0, 2): -1, (): 10}
>>> G = DictArithmetic( >>> {(0, 1): -4, (0, 2): -1, (0,): 3, (1,): 2, (): 2} >>> ) >>> D = G.subgraph({0, 2}) >>> D {(0, 2): -1, (0,): 3}
>>> G = DictArithmetic( >>> {(0, 1): -4, (0, 2): -1, (0,): 3, (1,): 2, (): 2} >>> ) >>> D = G.subgraph({0, 1}, {2: -10}) >>> D {(0, 1): -4, (0,): 13, (1,): 2}
>>> G = DictArithmetic( >>> {(0, 1): -4, (0, 2): -1, (0,): 3, (1,): 2, (): 2} >>> ) >>> D = G.subgraph({0, 1}) >>> D {(0, 1): -4, (0,): 3, (1,): 2}
- subs(*args, **kwargs)
subs.
Replace any
sympy
symbols that are used in the dict with values. Please seehelp(sympy.Symbol.subs)
for more info.- Parameters
arguments (substitutions.) – Same parameters as are inputted into
sympy.Symbol.subs
.- Returns
res – Same as
self
but with all the symbols replaced with values.- Return type
DictArithmetic object.
- subvalue(values)
subvalue.
Replace each element in
self
with a value invalues
if it exists.- Parameters
values (dict.) – For each node
v
inself
that is invalues
, we replace the node withvalues[v]
.- Returns
D
- Return type
same as type(self)
Examples
>>> G = DictArithmetic( >>> {(0, 1): -4, (0, 2): -1, (0,): 3, (1,): 2, (): 2 >>> } >>> D = G.subvalue({0: 2}) >>> D {(1,): -6, (2,): -2, (): 8}
>>> G = DictArtihmetic( >>> {(0, 1): -4, (0, 2): -1, (0,): 3, (1,): 2, (): 2 >>> } >>> D = G.subvalue({2: -3}) >>> D {(0, 1): -4, (0,): 6, (1,): 2, (): 2}
>>> G = PUBO( >>> {(0, 1): -4, (0, 2): -1, (0,): 3, (1,): 2, (): 2 >>> } >>> D = G.subvalue({2: -3}) >>> D {(0, 1): -4, (0,): 6, (1,): 2, (): 2}
- update(*args, **kwargs)
update.
Update the dictionary but following all the conventions of this class.
- Parameters
arguments (defines a dictionary, ie
d = dict(*args, **kwargs)
.) – Each element in d will be added in place to this instance following all the required convensions.
- values() an object providing a view on D's values
BO
- class qubovert.utils.BO(*args, **kwargs)
BO.
Parent class for some Binary Optimization classes, such as
qubovert.QUBO
,qubovert.QUSO
, etc.BO inherits some methods and attributes the
DictArithmetic
class. Seehelp(qubovert.utils.DictArithmetic)
.BO inherits some methods and attributes the
Conversions
class. Seehelp(qubovert.utils.Conversions)
.__init__.
This class deals with Binary Optimization models. See child classes for info on inputs.
- Parameters
arguments (Defined in child classes.) –
- property mapping
mapping.
Return a copy of the mapping dictionary that maps the provided labels to integers from 0 to n-1, where n is the number of variables in the problem.
- Returns
mapping – Dictionary that maps provided labels to integer labels.
- Return type
dict.
- property max_index
max_index.
Return the maximum label of the integer labeled version of the problem.
- Returns
m
- Return type
int.
- property reverse_mapping
reverse_mapping.
Return a copy of the reverse_mapping dictionary that maps the integer labels to the provided labels. Opposite of
mapping
.- Returns
reverse_mapping – Dictionary that maps integer labels to provided labels.
- Return type
dict.
- set_mapping(*args, **kwargs)
set_mapping.
BO
sublcasses automatically create a mapping from variable names to integers as they are being built. However, the mapping is based on the order in which elements are entered and therefore may not be as desired. Of course, theconvert_solution
method keeps track of the mapping and can/should always be used. But if you want a consistent mapping, thenset_mapping
can be used.Consider the following examples (we use the
qubovert.QUBO
class for the examples, which is a subclass ofBO
).Example 1:
>>> from qubovert import QUBO >>> Q = QUBO() >>> Q[(0,)] += 1 >>> Q[(1,)] += 2 >>> Q.mapping {0: 0, 1: 1} >>> Q.to_qubo() {(0,): 1, (1,): 2}
Example 2:
>>> from qubovert import QUBO >>> Q = QUBO() >>> Q[(1,)] += 2 >>> Q[(0,)] += 1 >>> Q.mapping {0: 1, 1: 0} >>> Q.to_qubo() {(0,): 2, (1,): 1}
To ensure consistency in mappings, you can provide your own mapping with
set_mapping
. See the following modified examples.Modified example 1:
>>> from qubovert import QUBO >>> Q = QUBO() >>> Q[(0,)] += 1 >>> Q[(1,)] += 2 >>> Q.set_mapping({0: 0, 1: 1}) >>> Q.mapping {0: 0, 1: 1} >>> Q.to_qubo() {(0,): 1, (1,): 2}
Modified example 2:
>>> from qubovert import QUBO >>> Q = QUBO() >>> Q[(1,)] += 2 >>> Q[(0,)] += 1 >>> Q.set_mapping({0: 0, 1: 1}) >>> Q.mapping {0: 0, 1: 1} >>> Q.to_qubo() {(0,): 1, (1,): 2}
- Parameters
arguments (defines a dictionary with
d = dict(*args, **kwargs)
.) –d
will become the mapping. Seehelp(self.mapping)
Notes
Using
set_mapping
to set the mapping will also automatically set thereverse_mapping
, so there is no need to call bothset_mapping
andset_reverse_mapping
.
- set_reverse_mapping(*args, **kwargs)
set_reverse_mapping.
Same as
set_mapping
but reversed. Seehelp(self.reverse_mapping)
andhelp(self.set_mapping)
.- Parameters
arguments (defines a dictionary with
d = dict(*args, **kwargs)
.) –d
will become the reverse mapping. Seehelp(self.reverse_mapping)
.
Notes
Using
set_reverse_mapping
to set the mapping will also automatically set themapping
, so there is no need to call bothset_mapping
andset_reverse_mapping
.
- to_enumerated()
to_enumerated.
Return the default enumerated Matrix object.
If
self
is a QUBO,self.to_enumerated()
is equivalent toself.to_qubo()
.If
self
is a QUSO,self.to_enumerated()
is equivalent toself.to_quso()
.If
self
is a PUBO or PCBO,self.to_enumerated()
is equivalent toself.to_pubo()
.If
self
is a PUSO or PCSO,self.to_enumerated()
is equivalent toself.to_puso()
.- Returns
res – If
self
is a QUBO type, then this method returns the corresponding QUBOMatrix type. Ifself
is a QUSO type, then this method returns the corresponding QUSOMatrix type. Ifself
is a PUBO or PCBO type, then this method returns the corresponding PUBOMatrix type. Ifself
is a PUSO or PCSO type, then this method returns the corresponding PUSOMatrix type.- Return type
QUBOMatrix, QUSOMatrix, PUBOMatrix, or PUSOMatrix object.
- to_pubo(*args, **kwargs)
to_pubo.
Create and return upper triangular PUBO representing the problem. Should be implemented in child classes. If this method is not implemented in the child class, then it simply calls
to_puso
orto_qubo
and converts the puso or QUBO formulations to a PUBO formulation.- Parameters
arguments (Defined in the child class.) – They should be parameters that define lagrange multipliers or factors in the QUBO.
- Returns
P – The upper triangular PUBO matrix, a PUBOMatrix object. For most practical purposes, you can use PUBOMatrix in the same way as an ordinary dictionary. For more information, see
help(qubovert.utils.PUBOMatrix)
.- Return type
qubovert.utils.PUBOMatrix object.
- Raises
RecursionError` if neither to_pubo nor to_puso are define –
in the subclass. –
- to_puso(*args, **kwargs)
to_puso.
Create and return PUSO model representing the problem. Should be implemented in child classes. If this method is not implemented in the child class, then it simply calls
to_pubo
orto_quso
and converts to a PUSO formulation.- Parameters
arguments (Defined in the child class.) – They should be parameters that define lagrange multipliers or factors in the QUSO model.
- Returns
H – For most practical purposes, you can use PUSOMatrix in the same way as an ordinary dictionary. For more information, see
help(qubovert.utils.PUSOMatrix)
.- Return type
qubovert.utils.PUSOMatrix object.
- Raises
RecursionError` if neither to_pubo nor to_puso are define –
in the subclass. –
- to_qubo(*args, **kwargs)
to_qubo.
Create and return upper triangular QUBO representing the problem. Should be implemented in child classes. If this method is not implemented in the child class, then it simply calls
to_quso
and converts the quso formulation to a QUBO formulation.- Parameters
arguments (Defined in the child class.) – They should be parameters that define lagrange multipliers or factors in the QUBO.
- Returns
Q – The upper triangular QUBO matrix, a QUBOMatrix object. For most practical purposes, you can use QUBOMatrix in the same way as an ordinary dictionary. For more information, see
help(qubovert.utils.QUBOMatrix)
.- Return type
qubovert.utils.QUBOMatrix object.
- Raises
RecursionError` if neither to_qubo nor to_quso are define –
in the subclass. –
- to_quso(*args, **kwargs)
to_quso.
Create and return QUSO model representing the problem. Should be implemented in child classes. If this method is not implemented in the child class, then it simply calls
to_qubo
and converts the QUBO formulation to an QUSO formulation.- Parameters
arguments (Defined in the child class.) – They should be parameters that define lagrange multipliers or factors in the QUSO model.
- Returns
L – The upper triangular coupling matrix, where two element tuples represent couplings and one element tuples represent fields. For most practical purposes, you can use IsingCoupling in the same way as an ordinary dictionary. For more information, see
help(qubovert.utils.QUSOMatrix)
.- Return type
qubovert.utils.QUSOMatrix object.
- Raises
RecursionError` if neither to_qubo nor to_quso are define –
in the subclass. –
Conversions
- class qubovert.utils.Conversions
Conversions.
This is a parent class that defines the functions
to_qubo
,to_quso
,to_pubo
, andto_puso
. Any subclass that inherits fromConversions
must supply at least one ofto_qubo
orto_quso
. And at least one ofto_pubo
orto_puso
.- to_pubo(*args, **kwargs)
to_pubo.
Create and return upper triangular PUBO representing the problem. Should be implemented in child classes. If this method is not implemented in the child class, then it simply calls
to_puso
orto_qubo
and converts the puso or QUBO formulations to a PUBO formulation.- Parameters
arguments (Defined in the child class.) – They should be parameters that define lagrange multipliers or factors in the QUBO.
- Returns
P – The upper triangular PUBO matrix, a PUBOMatrix object. For most practical purposes, you can use PUBOMatrix in the same way as an ordinary dictionary. For more information, see
help(qubovert.utils.PUBOMatrix)
.- Return type
qubovert.utils.PUBOMatrix object.
- Raises
RecursionError` if neither to_pubo nor to_puso are define –
in the subclass. –
- to_puso(*args, **kwargs)
to_puso.
Create and return PUSO model representing the problem. Should be implemented in child classes. If this method is not implemented in the child class, then it simply calls
to_pubo
orto_quso
and converts to a PUSO formulation.- Parameters
arguments (Defined in the child class.) – They should be parameters that define lagrange multipliers or factors in the QUSO model.
- Returns
H – For most practical purposes, you can use PUSOMatrix in the same way as an ordinary dictionary. For more information, see
help(qubovert.utils.PUSOMatrix)
.- Return type
qubovert.utils.PUSOMatrix object.
- Raises
RecursionError` if neither to_pubo nor to_puso are define –
in the subclass. –
- to_qubo(*args, **kwargs)
to_qubo.
Create and return upper triangular QUBO representing the problem. Should be implemented in child classes. If this method is not implemented in the child class, then it simply calls
to_quso
and converts the quso formulation to a QUBO formulation.- Parameters
arguments (Defined in the child class.) – They should be parameters that define lagrange multipliers or factors in the QUBO.
- Returns
Q – The upper triangular QUBO matrix, a QUBOMatrix object. For most practical purposes, you can use QUBOMatrix in the same way as an ordinary dictionary. For more information, see
help(qubovert.utils.QUBOMatrix)
.- Return type
qubovert.utils.QUBOMatrix object.
- Raises
RecursionError` if neither to_qubo nor to_quso are define –
in the subclass. –
- to_quso(*args, **kwargs)
to_quso.
Create and return QUSO model representing the problem. Should be implemented in child classes. If this method is not implemented in the child class, then it simply calls
to_qubo
and converts the QUBO formulation to an QUSO formulation.- Parameters
arguments (Defined in the child class.) – They should be parameters that define lagrange multipliers or factors in the QUSO model.
- Returns
L – The upper triangular coupling matrix, where two element tuples represent couplings and one element tuples represent fields. For most practical purposes, you can use IsingCoupling in the same way as an ordinary dictionary. For more information, see
help(qubovert.utils.QUSOMatrix)
.- Return type
qubovert.utils.QUSOMatrix object.
- Raises
RecursionError` if neither to_qubo nor to_quso are define –
in the subclass. –