pygsti.baseobjs.qubitgraph.QubitGraph#
- class QubitGraph(qubit_labels, initial_connectivity=None, initial_edges=None, directed=True, direction_names=None)#
Bases:
NicelySerializableA directed or undirected graph data structure used to represent geometrical layouts of qubits or qubit gates.
Qubits are nodes in the graph (and can be labeled), and edges represent the ability to perform one or more types of gates between qubits (equivalent, usually, to geometrical proximity).
- Parameters:
qubit_labels (list) – A list of string or integer labels of the qubits. The length of this list equals the number of qubits (nodes) in the graph.
initial_connectivity (numpy.ndarray, optional) – A (nqubits, nqubits) boolean or integer array giving the initial connectivity of the graph. If an integer array, then 0 indicates no edge and positive integers indicate present edges in the “direction” given by the positive integer. For example 1 may correspond to “left” and 2 to “right”. Names must be associated with these directions using direction_names. If a boolean array, if there’s an edge from qubit i to j then initial_connectivity[i,j]=True (integer indices of qubit labels are given by their position in qubit_labels). When directed=False, only the upper triangle is used.
initial_edges (list) – A list of (qubit_label1, qubit_label2) 2-tuples or (qubit_label1, qubit_label2, direction) 3-tuples specifying which edges are initially present. direction can either be a positive integer, similar to those used in initial_connectivity (in which case direction_names must be specified) or a string labeling the direction, e.g. “left”.
directed (bool, optional) – Whether the graph is directed or undirected. Directions can only be used when directed=True.
direction_names (iterable, optional) – A list (or tuple, etc) of string-valued direction names such as “left” or “right”. These strings label the directions referenced by index in either initial_connectivity or initial_edges, and this argument is required whenever such indices are used.
Initialize a new QubitGraph.
Can specify at most one of initial_connectivity and initial_edges.
- Parameters:
qubit_labels (list) – A list of string or integer labels of the qubits. The length of this list equals the number of qubits (nodes) in the graph.
initial_connectivity (numpy.ndarray, optional) – A (nqubits, nqubits) boolean or integer array giving the initial connectivity of the graph. If an integer array, then 0 indicates no edge and positive integers indicate present edges in the “direction” given by the positive integer. For example 1 may correspond to “left” and 2 to “right”. Names must be associated with these directions using direction_names. If a boolean array, if there’s an edge from qubit i to j then initial_connectivity[i,j]=True (integer indices of qubit labels are given by their position in qubit_labels). When directed=False, only the upper triangle is used.
initial_edges (list) – A list of (qubit_label1, qubit_label2) 2-tuples or (qubit_label1, qubit_label2, direction) 3-tuples specifying which edges are initially present. direction can either be a positive integer, similar to those used in initial_connectivity (in which case direction_names must be specified) or a string labeling the direction, e.g. “left”.
directed (bool, optional) – Whether the graph is directed or undirected. Directions can only be used when directed=True.
direction_names (iterable, optional) – A list (or tuple, etc) of string-valued direction names such as “left” or “right”. These strings label the directions referenced by index in either initial_connectivity or initial_edges, and this argument is required whenever such indices are used.
Methods
__init__(qubit_labels[, ...])Initialize a new QubitGraph.
add_edge(node1, node2[, direction])Add an edge between the qubits labeled by node1 and node2.
add_edges(edges)Add edges (list of tuple pairs) to graph.
add_mongodb_write_ops(write_ops, mongodb[, ...])Accumulate write and update operations for writing this object to a MongoDB database.
common_graph([num_qubits, geometry, ...])Create a QubitGraph that is one of several standard types of graphs.
connected_combos(possible_nodes, size)Computes the number of different connected subsets of possible_nodes containing size nodes.
copy()Make a copy of this graph.
dump(f[, format])Serializes and writes this object to a given output stream.
dumps([format])Serializes this object and returns it as a string.
edges([double_for_undirected, ...])Get a list of the edges in this graph as 2-tuples of node/qubit labels).
Finds all subgraphs (connected sets of vertices) up to the full graph size.
from_mongodb(mongodb, doc_id, **kwargs)Create and initialize an object from a MongoDB instance.
from_mongodb_doc(mongodb, collection_name, ...)Create and initialize an object from a MongoDB instance and pre-loaded primary document.
from_nice_serialization(state)Create and initialize an object from a "nice" serialization.
has_edge(edge)Is edge an edge in this graph.
is_connected(node1, node2)Is node1 connected to node2 (does there exist a path of any length between them?)
Computes whether this graph is connected (there exist paths between every pair of nodes).
is_connected_subgraph(nodes)Do a give set of nodes form a connected subgraph?
is_directly_connected(node1, node2)Is node1 directly connected to node2 (does there exist an edge between them?)
load(f[, format])Load an object of this type, or a subclass of this type, from an input stream.
loads(s[, format])Load an object of this type, or a subclass of this type, from a string.
map_qubit_labels(mapper)Creates a new QubitGraph whose qubit (node) labels are updated according to the mapping function mapper.
move_in_direction(start_node, direction)Get the node that is one step in direction of start_node.
move_in_directions(start_node, directions)The node you end up on after moving in directions from start_node.
radius(base_nodes, max_hops)Find all the nodes reachable in max_hops from any node in base_nodes.
read(path[, format])Read an object of this type, or a subclass of this type, from a file.
remove_edge(node1, node2)Add an edge between the qubits labeled by node1 and node2.
remove_from_mongodb(mongodb, doc_id[, ...])Remove the documents corresponding to an instance of this class from a MongoDB database.
remove_me_from_mongodb(mongodb[, session, ...])Resolve a "relative nodelabel" into an actual node in this graph.
shortest_path(node1, node2)Get the shortest path between two nodes (qubits).
shortest_path_distance(node1, node2)Get the distance of the shortest path between node1 and node2.
Returns a matrix of shortest path distances.
shortest_path_edges(node1, node2)Like
shortest_path(), but returns a list of (nodeA,nodeB) tuples.shortest_path_intersect(node1, node2, ...)Check whether the shortest path between node1 and node2 contains any of the nodes in nodes_to_intersect.
Returns a matrix of predecessors used to construct the shortest path between two nodes.
subgraph(nodes_to_keep[, reset_nodes, ...])Return a graph that includes only nodes_to_keep and the edges between them.
Serialize this object in a way that adheres to "niceness" rules of common text file formats.
write(path, **format_kwargs)Writes this object to a file.
write_to_mongodb(mongodb[, session, ...])Write this object to a MongoDB database.
Attributes
collection_nameAll the node labels of this graph.
- add_edge(node1, node2, direction=None)#
Add an edge between the qubits labeled by node1 and node2.
- Parameters:
node1 (str or int) – Qubit (node) label.
node2 (str or int) – Qubit (node) label.
direction (str or int, optional) – Either a direction name or a direction indicex
- Return type:
None
- add_edges(edges)#
Add edges (list of tuple pairs) to graph.
- Parameters:
edges (list) – A list of (qubit_label1, qubit_label2) 2-tuples.
- Return type:
None
- add_mongodb_write_ops(write_ops, mongodb, overwrite_existing=False, **kwargs)#
Accumulate write and update operations for writing this object to a MongoDB database.
Similar to
write_to_mongodb()but collects write operations instead of actually executing any write operations on the database. This function may be preferred towrite_to_mongodb()when this object is being written as a part of a larger entity and executing write operations is saved until the end.As in
write_to_mongodb(), self.collection_name is the collection name and _id is either: 1) the ID used by a previous write or initial read-in, if one exists, OR 2) a new random bson.objectid.ObjectId- Parameters:
write_ops (WriteOpsByCollection) – An object that keeps track of pymongo write operations on a per-collection basis. This object accumulates write operations to be performed at some point in the future.
mongodb (pymongo.database.Database) – The MongoDB instance to write data to.
overwrite_existing (bool, optional) – Whether existing documents should be overwritten. The default of False causes a ValueError to be raised if a document with the given _id already exists and is different from what is being written.
**kwargs (dict) – Additional keyword arguments potentially used by subclass implementations. Any arguments allowed by a subclass’s _add_auxiliary_write_ops_and_update_doc method is allowed here.
- Returns:
The identifier (_id value) of the main document that was written.
- Return type:
bson.objectid.ObjectId
- classmethod common_graph(num_qubits=0, geometry='line', directed=True, qubit_labels=None, all_directions=False)#
Create a QubitGraph that is one of several standard types of graphs.
- Parameters:
num_qubits (int, optional) – The number of qubits (nodes in the graph).
geometry ({"line","ring","grid","torus"}) – The type of graph. What these correspond to should be self-evident.
directed (bool, optional) – Whether the graph is directed or undirected.
qubit_labels (iterable, optional) – The labels for the qubits. Must be of length num_qubits. If None, then the integers from 0 to num_qubits-1 are used.
all_directions (bool, optional) – Whether to include edges with all directions. Typically it only makes sense to set this to True when directed=True also.
- Return type:
- connected_combos(possible_nodes, size)#
Computes the number of different connected subsets of possible_nodes containing size nodes.
- Parameters:
possible_nodes (list) – A list of node (qubit) labels.
size (int) – The size of the connected subsets being sought (counted).
- Return type:
int
- copy()#
Make a copy of this graph.
- Return type:
- dump(f, format='json', **format_kwargs)#
Serializes and writes this object to a given output stream.
- Parameters:
f (file-like) – A writable output stream.
format ({'json', 'repr'}) – The format to write.
format_kwargs (dict, optional) – Additional arguments specific to the format being used. For example, the JSON format accepts indent as an argument because json.dump does.
- Return type:
None
- dumps(format='json', **format_kwargs)#
Serializes this object and returns it as a string.
- Parameters:
format ({'json', 'repr'}) – The format to write.
format_kwargs (dict, optional) – Additional arguments specific to the format being used. For example, the JSON format accepts indent as an argument because json.dump does.
- Return type:
str
- edges(double_for_undirected=False, include_directions=False)#
Get a list of the edges in this graph as 2-tuples of node/qubit labels).
When undirected, the index of the 2-tuple’s first label will always be less than its second unless double_for_undirected == True, in which case both directed edges are included. The edges are sorted (by label index) in ascending order.
- Parameters:
double_for_undirected (bool, optional) – Whether, for the case of an undirected graph, two 2-tuples, giving both edge directions, should be included in the returned list.
include_directions (bool, optional) – Whether to include direction labels. If True and directions are present, a list of (node1, node2, direction_name) 3-tuples is returned instead of the usual (node1, node2) 2-tuples.
- Return type:
list
- find_all_connected_sets()#
Finds all subgraphs (connected sets of vertices) up to the full graph size.
Graph edges are treated as undirected.
- Returns:
A dictionary with integer keys. The value of key k is a list of all the subgraphs of length k. A subgraph is given as a tuple of sorted vertex labels.
- Return type:
dict
- classmethod from_mongodb(mongodb, doc_id, **kwargs)#
Create and initialize an object from a MongoDB instance.
- Parameters:
mongodb (pymongo.database.Database) – The MongoDB instance to load from.
doc_id (bson.objecctid.ObjectId or dict) – The object ID or filter used to find a single object ID within the database. This document is loaded from the collection given by the collection_name attribute of this class.
**kwargs (dict) – Additional keyword arguments potentially used by subclass implementations. Any arguments allowed by a subclass’s _create_obj_from_doc_and_mongodb method is allowed here.
- Return type:
object
- classmethod from_mongodb_doc(mongodb, collection_name, doc, **kwargs)#
Create and initialize an object from a MongoDB instance and pre-loaded primary document.
- Parameters:
mongodb (pymongo.database.Database) – The MongoDB instance to load from.
collection_name (str) – The collection name within mongodb that doc was loaded from. This is needed for the sole purpose of setting the created (returned) object’s database “coordinates”.
doc (dict) – The already-retrieved main document for the object being loaded. This takes the place of giving an identifier for this object.
**kwargs (dict) – Additional keyword arguments potentially used by subclass implementations. Any arguments allowed by a subclass’s _create_obj_from_doc_and_mongodb method is allowed here.
- Return type:
object
- classmethod from_nice_serialization(state)#
Create and initialize an object from a “nice” serialization.
A “nice” serialization here means one created by a prior call to to_nice_serialization using this class or a subclass of it. Nice serializations adhere to additional rules (e.g. that dictionary keys must be strings) that make them amenable to common file formats (e.g. JSON).
The state argument is typically a dictionary containing ‘module’ and ‘state’ keys specifying the type of object that should be created. This type must be this class or a subclass of it.
- Parameters:
state (object) – An object, usually a dictionary, representing the object to de-serialize.
- Return type:
object
- has_edge(edge)#
Is edge an edge in this graph.
Note that if this graph is undirected, either node order in edge will return True.
- Parameters:
edge (tuple) – (node1,node2) tuple specifying the edge.
- Return type:
bool
- is_connected(node1, node2)#
Is node1 connected to node2 (does there exist a path of any length between them?)
- Parameters:
node1 (str or int) – Qubit (node) label.
node2 (str or int) – Qubit (node) label.
- Return type:
bool
- is_connected_graph()#
Computes whether this graph is connected (there exist paths between every pair of nodes).
- Return type:
bool
- is_connected_subgraph(nodes)#
Do a give set of nodes form a connected subgraph?
That is, does there exist a path from every node in nodes to every other node in nodes using only the edges between the nodes in nodes.
- Parameters:
nodes (list) – A list of node (qubit) labels.
- Return type:
bool
- is_directly_connected(node1, node2)#
Is node1 directly connected to node2 (does there exist an edge between them?)
- Parameters:
node1 (str or int) – Qubit (node) label.
node2 (str or int) – Qubit (node) label.
- Return type:
bool
- classmethod load(f, format='json')#
Load an object of this type, or a subclass of this type, from an input stream.
- Parameters:
f (file-like) – An open input stream to read from.
format ({'json'}) – The format of the input stream data.
- Return type:
- classmethod loads(s, format='json')#
Load an object of this type, or a subclass of this type, from a string.
- Parameters:
s (str) – The serialized object.
format ({'json'}) – The format of the string data.
- Return type:
- map_qubit_labels(mapper)#
Creates a new QubitGraph whose qubit (node) labels are updated according to the mapping function mapper.
- Parameters:
mapper (dict or function) – A dictionary whose keys are the existing self.node_names values and whose value are the new labels, or a function which takes a single (existing qubit-label) argument and returns a new qubit label.
- Return type:
- move_in_direction(start_node, direction)#
Get the node that is one step in direction of start_node.
- Parameters:
start_node (int or str) – the starting point (a node label of this graph)
direction (str or int) – the name of a direction or its index within this graphs .directions member.
- Returns:
the node in the given direction or None if there is no node in that direction (e.g. if you reach the end of a chain).
- Return type:
str or int or None
- move_in_directions(start_node, directions)#
The node you end up on after moving in directions from start_node.
- Parameters:
start_node (str or int) – Qubit (node) label.
directions (iterable) – A sequence of direction names.
- Returns:
The ending node label or None if the directions were invalid.
- Return type:
str or int or None
- radius(base_nodes, max_hops)#
Find all the nodes reachable in max_hops from any node in base_nodes.
Get a (sorted) array of node labels that can be reached from traversing at most max_hops edges starting from a node (vertex) in base_nodes.
- Parameters:
base_nodes (iterable) – A list of node/qubit labels giving the possible starting locations.
max_hops (int) – The maximum number of hops (see above).
- Returns:
A list of the node labels reachable from base_nodes in at most max_hops edge traversals.
- Return type:
list
- classmethod read(path, format=None)#
Read an object of this type, or a subclass of this type, from a file.
- Parameters:
path (str or Path or file-like) – The filename to open or an already open input stream.
format ({'json', None}) – The format of the file. If None this is determined automatically by the filename extension of a given path.
- Return type:
- remove_edge(node1, node2)#
Add an edge between the qubits labeled by node1 and node2.
- Parameters:
node1 (str or int) – Qubit (node) label.
node2 (str or int) – Qubit (node) label.
- Return type:
None
- classmethod remove_from_mongodb(mongodb, doc_id, collection_name=None, session=None, recursive='default')#
Remove the documents corresponding to an instance of this class from a MongoDB database.
- Parameters:
mongodb (pymongo.database.Database) – The MongoDB instance to remove documents from.
doc_id (bson.objectid.ObjectId) – The identifier of the root document stored in the database.
collection_name (str, optional) – the MongoDB collection within mongodb where the main document resides. If None, then <this_class>.collection_name is used (which is usually what you want).
session (pymongo.client_session.ClientSession, optional) – MongoDB session object to use when interacting with the MongoDB database. This can be used to implement transactions among other things.
recursive (RecursiveRemovalSpecification, optional) – An object that filters the type of documents that are removed. Used when working with inter-related experiment designs, data, and results objects to only remove the types of documents you know aren’t being shared with other documents.
- Return type:
None
- resolve_relative_nodelabel(relative_nodelabel, target_labels)#
Resolve a “relative nodelabel” into an actual node in this graph.
Relative node labels can use “@” to index elements of target_labels and can contain “+<dir>” directives to move along directions defined in this graph.
- Parameters:
relative_nodelabel (int or str) – An absolute or relative node-label. For example: 0, “@0”, “@0+right”, “@1+left+up”
target_labels (list or tuple) – A list of (absolute) node labels present in this graph that may be referred to using the “@” syntax within relative_nodelabel.
- Return type:
int or str
- shortest_path(node1, node2)#
Get the shortest path between two nodes (qubits).
- Parameters:
node1 (str or int) – Qubit (node) label.
node2 (str or int) – Qubit (node) label.
- Returns:
A list of the node labels to traverse.
- Return type:
list
- shortest_path_distance(node1, node2)#
Get the distance of the shortest path between node1 and node2.
- Parameters:
node1 (str or int) – Qubit (node) label.
node2 (str or int) – Qubit (node) label.
- Return type:
int
- shortest_path_distance_matrix()#
Returns a matrix of shortest path distances.
This matrix is indexed by the integer-index of each node label (as specified to __init__). The list of index-ordered node labels is given by
node_names().- Returns:
A boolean array of shape (n,n) where n is the number of nodes in this graph.
- Return type:
numpy.ndarray
- shortest_path_edges(node1, node2)#
Like
shortest_path(), but returns a list of (nodeA,nodeB) tuples.These tuples define a path from node1 to node2, so the first tuple’s nodeA == node1 and the final tuple’s nodeB == node2.
- Parameters:
node1 (str or int) – Qubit (node) label.
node2 (str or int) – Qubit (node) label.
- Returns:
A list of the edges (2-tuples of node labels) to traverse.
- Return type:
list
- shortest_path_intersect(node1, node2, nodes_to_intersect)#
Check whether the shortest path between node1 and node2 contains any of the nodes in nodes_to_intersect.
- Parameters:
node1 (str or int) – Qubit (node) label.
node2 (str or int) – Qubit (node) label.
nodes_to_intersect (list) – A list of node labels.
- Returns:
True if the shortest path intersects any node in nodeToIntersect.
- Return type:
bool
- shortest_path_predecessor_matrix()#
Returns a matrix of predecessors used to construct the shortest path between two nodes.
This matrix is indexed by the integer-index of each node label (as specified to __init__). The list of index-ordered node labels is given by
node_names().- Returns:
A boolean array of shape (n,n) where n is the number of nodes in this graph.
- Return type:
numpy.ndarray
- subgraph(nodes_to_keep, reset_nodes=False, include_directions=True)#
Return a graph that includes only nodes_to_keep and the edges between them.
- Parameters:
nodes_to_keep (list) – A list of node labels defining the subgraph to return.
reset_nodes (bool, optional) – If True, nodes of returned subgraph are relabelled to be the integers starting at 0 (in 1-1 correspondence with the ordering in nodes_to_keep).
include_directions (bool, optional) – Whether the subgraph should retain the direction information of the parent graph. Defaults to True.
- Return type:
- to_nice_serialization()#
Serialize this object in a way that adheres to “niceness” rules of common text file formats.
- Returns:
Usually a dictionary representing the serialized object, but may also be another native Python type, e.g. a string or list.
- Return type:
object
- write(path, **format_kwargs)#
Writes this object to a file.
- Parameters:
path (str or Path) – The name of the file that is written.
format_kwargs (dict, optional) – Additional arguments specific to the format being used. For example, the JSON format accepts indent as an argument because json.dump does.
- Return type:
None
- write_to_mongodb(mongodb, session=None, overwrite_existing=False, **kwargs)#
Write this object to a MongoDB database.
The collection name used is self.collection_name, and the _id is either: 1) the ID used by a previous write or initial read-in, if one exists, OR 2) a new random bson.objectid.ObjectId
- Parameters:
mongodb (pymongo.database.Database) – The MongoDB instance to write data to.
session (pymongo.client_session.ClientSession, optional) – MongoDB session object to use when interacting with the MongoDB database. This can be used to implement transactions among other things.
overwrite_existing (bool, optional) – Whether existing documents should be overwritten. The default of False causes a ValueError to be raised if a document with the given _id already exists and is different from what is being written.
**kwargs (dict) – Additional keyword arguments potentially used by subclass implementations. Any arguments allowed by a subclass’s _add_auxiliary_write_ops_and_update_doc method is allowed here.
- Returns:
The identifier (_id value) of the main document that was written.
- Return type:
bson.objectid.ObjectId
- property node_names#
All the node labels of this graph.
These correspond to integer indices where appropriate, e.g. for
shortest_path_distance_matrix().- Return type:
tuple