signature
stringlengths
8
3.44k
body
stringlengths
0
1.41M
docstring
stringlengths
1
122k
id
stringlengths
5
17
def is_matching(edges):
return len(set().union(*edges)) == len(edges) * <NUM_LIT:2><EOL>
Determines whether the given set of edges is a matching. A matching is a subset of edges in which no node occurs more than once. Parameters ---------- edges : iterable A iterable of edges. Returns ------- is_matching : bool True if the given edges are a matching. Example ------- This example checks two sets of edges, both derived from a single Chimera unit cell, for a matching. Because every node in a Chimera unit cell connects to four other nodes in the cell, the first set, which contains all the edges, repeats each node 4 times; the second is a subset of those edges found using the `min_maximal_matching()` function. >>> import dwave_networkx as dnx >>> G = dnx.chimera_graph(1, 1, 4) >>> dnx.is_matching(G.edges()) False >>> dnx.is_matching({(0, 4), (1, 5), (2, 7), (3, 6)}) True
f14391:m2
def is_maximal_matching(G, matching):
touched_nodes = set().union(*matching)<EOL>if len(touched_nodes) != len(matching) * <NUM_LIT:2>:<EOL><INDENT>return False<EOL><DEDENT>for (u, v) in G.edges:<EOL><INDENT>if u not in touched_nodes and v not in touched_nodes:<EOL><INDENT>return False<EOL><DEDENT><DEDENT>return True<EOL>
Determines whether the given set of edges is a maximal matching. A matching is a subset of edges in which no node occurs more than once. The cardinality of a matching is the number of matched edges. A maximal matching is one where one cannot add any more edges without violating the matching rule. Parameters ---------- G : NetworkX graph The graph on which to check the maximal matching. edges : iterable A iterable of edges. Returns ------- is_matching : bool True if the given edges are a maximal matching. Example ------- This example checks two sets of edges, both derived from a single Chimera unit cell, for a matching. The first set (a matching) is a subset of the second, which was found using the `min_maximal_matching()` function. >>> import dwave_networkx as dnx >>> G = dnx.chimera_graph(1, 1, 4) >>> dnx.is_matching({(0, 4), (2, 7)}) True >>> dnx.is_maximal_matching(G,{(0, 4), (2, 7)}) False >>> dnx.is_maximal_matching(G,{(0, 4), (1, 5), (2, 7), (3, 6)}) True
f14391:m3
def _edge_mapping(G):
edge_mapping = {edge: idx for idx, edge in enumerate(G.edges)}<EOL>edge_mapping.update({(e1, e0): idx for (e0, e1), idx in edge_mapping.items()})<EOL>return edge_mapping<EOL>
Assigns a variable for each edge in G. (u, v) and (v, u) map to the same variable.
f14391:m4
def _maximal_matching_qubo(G, edge_mapping, magnitude=<NUM_LIT:1.>):
Q = {}<EOL>for (u, v) in G.edges:<EOL><INDENT>for edge in G.edges(u):<EOL><INDENT>x = edge_mapping[edge]<EOL>if (x, x) not in Q:<EOL><INDENT>Q[(x, x)] = -<NUM_LIT:1> * magnitude<EOL><DEDENT>else:<EOL><INDENT>Q[(x, x)] -= magnitude<EOL><DEDENT><DEDENT>for edge in G.edges(v):<EOL><INDENT>x = edge_mapping[edge]<EOL>if (x, x) not in Q:<EOL><INDENT>Q[(x, x)] = -<NUM_LIT:1> * magnitude<EOL><DEDENT>else:<EOL><INDENT>Q[(x, x)] -= magnitude<EOL><DEDENT><DEDENT>for e0 in G.edges(v):<EOL><INDENT>x0 = edge_mapping[e0]<EOL>for e1 in G.edges(u):<EOL><INDENT>x1 = edge_mapping[e1]<EOL>if x0 < x1:<EOL><INDENT>if (x0, x1) not in Q:<EOL><INDENT>Q[(x0, x1)] = magnitude<EOL><DEDENT>else:<EOL><INDENT>Q[(x0, x1)] += magnitude<EOL><DEDENT><DEDENT>else:<EOL><INDENT>if (x1, x0) not in Q:<EOL><INDENT>Q[(x1, x0)] = magnitude<EOL><DEDENT>else:<EOL><INDENT>Q[(x1, x0)] += magnitude<EOL><DEDENT><DEDENT><DEDENT><DEDENT><DEDENT>return Q<EOL>
Generates a QUBO that when combined with one as generated by _matching_qubo, induces a maximal matching on the given graph G. The variables in the QUBO are the edges, as given my edge_mapping. ground_energy = -1 * magnitude * |edges| infeasible_gap >= magnitude
f14391:m5
def _matching_qubo(G, edge_mapping, magnitude=<NUM_LIT:1.>):
Q = {}<EOL>for node in G:<EOL><INDENT>for edge0, edge1 in itertools.combinations(G.edges(node), <NUM_LIT:2>):<EOL><INDENT>v0 = edge_mapping[edge0]<EOL>v1 = edge_mapping[edge1]<EOL>Q[(v0, v1)] = magnitude<EOL><DEDENT><DEDENT>return Q<EOL>
Generates a QUBO that induces a matching on the given graph G. The variables in the QUBO are the edges, as given my edge_mapping. ground_energy = 0 infeasible_gap = magnitude
f14391:m6
def markov_network(potentials):
G = nx.Graph()<EOL>G.name = '<STR_LIT>'.format(potentials)<EOL>for clique, phis in potentials.items():<EOL><INDENT>num_vars = len(clique)<EOL>if not isinstance(phis, abc.Mapping):<EOL><INDENT>raise TypeError("<STR_LIT>")<EOL><DEDENT>elif not all(config in phis for config in itertools.product((<NUM_LIT:0>, <NUM_LIT:1>), repeat=num_vars)):<EOL><INDENT>raise ValueError("<STR_LIT>".format(clique))<EOL><DEDENT>if num_vars == <NUM_LIT:1>:<EOL><INDENT>u, = clique<EOL>G.add_node(u, potential=phis)<EOL><DEDENT>elif num_vars == <NUM_LIT:2>:<EOL><INDENT>u, v = clique<EOL>G.add_edge(u, v, potential=phis, order=(u, v))<EOL><DEDENT>else:<EOL><INDENT>raise ValueError("<STR_LIT>")<EOL><DEDENT><DEDENT>return G<EOL>
Creates a Markov Network from potentials. A Markov Network is also knows as a `Markov Random Field`_ Parameters ---------- potentials : dict[tuple, dict] A dict where the keys are either nodes or edges and the values are a dictionary of potentials. The potential dict should map each possible assignment of the nodes/edges to their energy. Returns ------- MN : :obj:`networkx.Graph` A markov network as a graph where each node/edge stores its potential dict as above. Examples -------- >>> potentials = {('a', 'b'): {(0, 0): -1, ... (0, 1): .5, ... (1, 0): .5, ... (1, 1): 2}} >>> MN = dnx.markov_network(potentials) >>> MN['a']['b']['potential'][(0, 0)] -1 .. _Markov Random Field: https://en.wikipedia.org/wiki/Markov_random_field
f14396:m0
def chimera_graph(m, n=None, t=None, create_using=None, node_list=None, edge_list=None, data=True, coordinates=False):
m = int(m)<EOL>if n is None:<EOL><INDENT>n = m<EOL><DEDENT>else:<EOL><INDENT>n = int(n)<EOL><DEDENT>if t is None:<EOL><INDENT>t = <NUM_LIT:4><EOL><DEDENT>else:<EOL><INDENT>t = int(t)<EOL><DEDENT>G = nx.empty_graph(<NUM_LIT:0>, create_using)<EOL>G.name = "<STR_LIT>" % (m, n, t)<EOL>construction = (("<STR_LIT>", "<STR_LIT>"), ("<STR_LIT>", m), ("<STR_LIT>", n),<EOL>("<STR_LIT>", t), ("<STR_LIT:data>", data),<EOL>("<STR_LIT>", "<STR_LIT>" if coordinates else "<STR_LIT:int>"))<EOL>G.graph.update(construction)<EOL>max_size = m * n * <NUM_LIT:2> * t <EOL>if edge_list is None:<EOL><INDENT>if coordinates:<EOL><INDENT>G.add_edges_from(((i, j, <NUM_LIT:0>, k0), (i, j, <NUM_LIT:1>, k1))<EOL>for i in range(n)<EOL>for j in range(m)<EOL>for k0 in range(t)<EOL>for k1 in range(t))<EOL>G.add_edges_from(((i, j, <NUM_LIT:1>, k), (i, j+<NUM_LIT:1>, <NUM_LIT:1>, k))<EOL>for i in range(m)<EOL>for j in range(n-<NUM_LIT:1>)<EOL>for k in range(t))<EOL>G.add_edges_from(((i, j, <NUM_LIT:0>, k), (i+<NUM_LIT:1>, j, <NUM_LIT:0>, k))<EOL>for i in range(m-<NUM_LIT:1>)<EOL>for j in range(n)<EOL>for k in range(t))<EOL><DEDENT>else:<EOL><INDENT>hoff = <NUM_LIT:2> * t<EOL>voff = n * hoff<EOL>mi = m * voff<EOL>ni = n * hoff<EOL>G.add_edges_from((k0, k1)<EOL>for i in range(<NUM_LIT:0>, ni, hoff)<EOL>for j in range(i, mi, voff)<EOL>for k0 in range(j, j + t)<EOL>for k1 in range(j + t, j + <NUM_LIT:2> * t))<EOL>G.add_edges_from((k, k + hoff)<EOL>for i in range(t, <NUM_LIT:2> * t)<EOL>for j in range(i, ni - hoff, hoff)<EOL>for k in range(j, mi, voff))<EOL>G.add_edges_from((k, k + voff)<EOL>for i in range(t)<EOL>for j in range(i, ni, hoff)<EOL>for k in range(j, mi - voff, voff))<EOL><DEDENT><DEDENT>else:<EOL><INDENT>G.add_edges_from(edge_list)<EOL><DEDENT>if node_list is not None:<EOL><INDENT>nodes = set(node_list)<EOL>G.remove_nodes_from(set(G) - nodes)<EOL>G.add_nodes_from(nodes) <EOL><DEDENT>if data:<EOL><INDENT>if coordinates:<EOL><INDENT>def checkadd(v, q):<EOL><INDENT>if q in G:<EOL><INDENT>G.node[q]['<STR_LIT>'] = v<EOL><DEDENT><DEDENT><DEDENT>else:<EOL><INDENT>def checkadd(v, q):<EOL><INDENT>if v in G:<EOL><INDENT>G.node[v]['<STR_LIT>'] = q<EOL><DEDENT><DEDENT><DEDENT>v = <NUM_LIT:0><EOL>for i in range(m):<EOL><INDENT>for j in range(n):<EOL><INDENT>for u in range(<NUM_LIT:2>):<EOL><INDENT>for k in range(t):<EOL><INDENT>checkadd(v, (i, j, u, k))<EOL>v += <NUM_LIT:1><EOL><DEDENT><DEDENT><DEDENT><DEDENT><DEDENT>return G<EOL>
Creates a Chimera lattice of size (m, n, t). A Chimera lattice is an m-by-n grid of Chimera tiles. Each Chimera tile is itself a bipartite graph with shores of size t. The connection in a Chimera lattice can be expressed using a node-indexing notation (i,j,u,k) for each node. * (i,j) indexes the (row, column) of the Chimera tile. i must be between 0 and m-1, inclusive, and j must be between 0 and n-1, inclusive. * u=0 indicates the left-hand nodes in the tile, and u=1 indicates the right-hand nodes. * k=0,1,...,t-1 indexes nodes within either the left- or right-hand shores of a tile. In this notation, two nodes (i, j, u, k) and (i', j', u', k') are neighbors if and only if: (i = i' AND j = j' AND u != u') OR (i = i' +/- 1 AND j = j' AND u = 0 AND u' = 0 AND k = k') OR (i = i' AND j = j' +/- 1 AND u = 1 AND u' = 1 AND k = k') The first of the three terms of the disjunction gives the bipartite connections within the tile. The second and third terms give the vertical and horizontal connections between blocks respectively. Node (i, j, u, k) is labeled by: label = i * n * 2 * t + j * 2 * t + u * t + k Parameters ---------- m : int Number of rows in the Chimera lattice. n : int (optional, default m) Number of columns in the Chimera lattice. t : int (optional, default 4) Size of the shore within each Chimera tile. create_using : Graph (optional, default None) If provided, this graph is cleared of nodes and edges and filled with the new graph. Usually used to set the type of the graph. node_list : iterable (optional, default None) Iterable of nodes in the graph. If None, calculated from (m, n, t). Note that this list is used to remove nodes, so any nodes specified not in `range(m * n * 2 * t)` are not added. edge_list : iterable (optional, default None) Iterable of edges in the graph. If None, edges are generated as described above. The nodes in each edge must be integer-labeled in `range(m * n * t * 2)`. data : bool (optional, default True) If True, each node has a `chimera_index attribute`. The attribute is a 4-tuple Chimera index as defined above. coordinates : bool (optional, default False) If True, node labels are 4-tuples, equivalent to the chimera_index attribute as above. In this case, the `data` parameter controls the existence of a `linear_index attribute`, which is an int Returns ------- G : NetworkX Graph An (m, n, t) Chimera lattice. Nodes are labeled by integers. Examples ======== >>> G = dnx.chimera_graph(1, 1, 2) # a single Chimera tile >>> len(G) 4 >>> list(G.nodes()) [0, 1, 2, 3] >>> list(G.nodes(data=True)) # doctest: +SKIP [(0, {'chimera_index': (0, 0, 0, 0)}), (1, {'chimera_index': (0, 0, 0, 1)}), (2, {'chimera_index': (0, 0, 1, 0)}), (3, {'chimera_index': (0, 0, 1, 1)})] >>> list(G.edges()) [(0, 2), (0, 3), (1, 2), (1, 3)]
f14397:m0
def find_chimera_indices(G):
<EOL>try:<EOL><INDENT>nlist = sorted(G.nodes)<EOL><DEDENT>except TypeError:<EOL><INDENT>nlist = G.nodes()<EOL><DEDENT>n_nodes = len(nlist)<EOL>chimera_indices = {}<EOL>if n_nodes == <NUM_LIT:0>:<EOL><INDENT>return chimera_indices<EOL><DEDENT>elif n_nodes == <NUM_LIT:1>:<EOL><INDENT>raise DWaveNetworkXException(<EOL>'<STR_LIT>')<EOL><DEDENT>elif n_nodes == <NUM_LIT:2>:<EOL><INDENT>return {nlist[<NUM_LIT:0>]: (<NUM_LIT:0>, <NUM_LIT:0>, <NUM_LIT:0>, <NUM_LIT:0>), nlist[<NUM_LIT:1>]: (<NUM_LIT:0>, <NUM_LIT:0>, <NUM_LIT:1>, <NUM_LIT:0>)}<EOL><DEDENT>coloring = color(G)<EOL>if coloring[nlist[<NUM_LIT:0>]] == <NUM_LIT:1>:<EOL><INDENT>coloring = {v: <NUM_LIT:1> - coloring[v] for v in coloring}<EOL><DEDENT>dia = diameter(G)<EOL>if dia == <NUM_LIT:2>:<EOL><INDENT>shore_indices = [<NUM_LIT:0>, <NUM_LIT:0>]<EOL>for v in nlist:<EOL><INDENT>u = coloring[v]<EOL>chimera_indices[v] = (<NUM_LIT:0>, <NUM_LIT:0>, u, shore_indices[u])<EOL>shore_indices[u] += <NUM_LIT:1><EOL><DEDENT>return chimera_indices<EOL><DEDENT>raise Exception('<STR_LIT>')<EOL>
Attempts to determine the Chimera indices of the nodes in graph G. See the `chimera_graph()` function for a definition of a Chimera graph and Chimera indices. Parameters ---------- G : NetworkX graph Should be a single-tile Chimera graph. Returns ------- chimera_indices : dict A dict of the form {node: (i, j, u, k), ...} where (i, j, u, k) is a 4-tuple of integer Chimera indices. Examples -------- >>> G = dnx.chimera_graph(1, 1, 4) >>> chimera_indices = dnx.find_chimera_indices(G) >>> G = nx.Graph() >>> G.add_edges_from([(0, 2), (1, 2), (1, 3), (0, 3)]) >>> chimera_indices = dnx.find_chimera_indices(G) >>> nx.set_node_attributes(G, chimera_indices, 'chimera_index')
f14397:m1
def chimera_elimination_order(m, n=None, t=None):
if n is None:<EOL><INDENT>n = m<EOL><DEDENT>if t is None:<EOL><INDENT>t = <NUM_LIT:4><EOL><DEDENT>index_flip = m > n<EOL>if index_flip:<EOL><INDENT>m, n = n, m<EOL><DEDENT>def chimeraI(m0, n0, k0, l0):<EOL><INDENT>if index_flip:<EOL><INDENT>return m*<NUM_LIT:2>*t*n0 + <NUM_LIT:2>*t*m0 + t*(<NUM_LIT:1>-k0) + l0<EOL><DEDENT>else:<EOL><INDENT>return n*<NUM_LIT:2>*t*m0 + <NUM_LIT:2>*t*n0 + t*k0 + l0<EOL><DEDENT><DEDENT>order = []<EOL>for n_i in range(n):<EOL><INDENT>for t_i in range(t):<EOL><INDENT>for m_i in range(m):<EOL><INDENT>order.append(chimeraI(m_i, n_i, <NUM_LIT:0>, t_i))<EOL><DEDENT><DEDENT><DEDENT>for n_i in range(n):<EOL><INDENT>for m_i in range(m):<EOL><INDENT>for t_i in range(t):<EOL><INDENT>order.append(chimeraI(m_i, n_i, <NUM_LIT:1>, t_i))<EOL><DEDENT><DEDENT><DEDENT>return order<EOL>
Provides a variable elimination order for a Chimera graph. A graph defined by chimera_graph(m,n,t) has treewidth max(m,n)*t. This function outputs a variable elimination order inducing a tree decomposition of that width. Parameters ---------- m : int Number of rows in the Chimera lattice. n : int (optional, default m) Number of columns in the Chimera lattice. t : int (optional, default 4) Size of the shore within each Chimera tile. Returns ------- order : list An elimination order that induces the treewidth of chimera_graph(m,n,t). Examples -------- >>> G = dnx.chimera_elimination_order(1, 1, 4) # a single Chimera tile
f14397:m2
def __init__(self, m, n=None, t=<NUM_LIT:4>):
self.args = m, m if n is None else n, t<EOL>
Provides coordinate converters for the chimera indexing scheme. Parameters ---------- m : int The number of rows in the Chimera lattice. n : int, optional (default m) The number of columns in the Chimera lattice. t : int, optional (default 4) The size of the shore within each Chimera tile.
f14397:c0:m0
def int(self, q):
i, j, u, k = q<EOL>m, n, t = self.args<EOL>return ((n*i + j)*<NUM_LIT:2> + u)*t + k<EOL>
Converts the chimera_index `q` into an linear_index Parameters ---------- q : tuple The chimera_index node label Returns ------- r : int The linear_index node label corresponding to q
f14397:c0:m1
def tuple(self, r):
m, n, t = self.args<EOL>r, k = divmod(r, t)<EOL>r, u = divmod(r, <NUM_LIT:2>)<EOL>i, j = divmod(r, n)<EOL>return i, j, u, k<EOL>
Converts the linear_index `q` into an chimera_index Parameters ---------- r : int The linear_index node label Returns ------- q : tuple The chimera_index node label corresponding to r
f14397:c0:m2
def ints(self, qlist):
m, n, t = self.args<EOL>return (((n*i + j)*<NUM_LIT:2> + u)*t + k for (i, j, u, k) in qlist)<EOL>
Converts a sequence of chimera_index node labels into linear_index node labels, preserving order Parameters ---------- qlist : sequence of ints The chimera_index node labels Returns ------- rlist : iterable of tuples The linear_lindex node lables corresponding to qlist
f14397:c0:m3
def tuples(self, rlist):
m, n, t = self.args<EOL>for r in rlist:<EOL><INDENT>r, k = divmod(r, t)<EOL>r, u = divmod(r, <NUM_LIT:2>)<EOL>i, j = divmod(r, n)<EOL>yield i, j, u, k<EOL><DEDENT>
Converts a sequence of linear_index node labels into chimera_index node labels, preserving order Parameters ---------- rlist : sequence of tuples The linear_index node labels Returns ------- qlist : iterable of ints The chimera_lindex node lables corresponding to rlist
f14397:c0:m4
def __pair_repack(self, f, plist):
ulist = f(u for p in plist for u in p)<EOL>for u in ulist:<EOL><INDENT>v = next(ulist)<EOL>yield u, v<EOL><DEDENT>
Flattens a sequence of pairs to pass through `f`, and then re-pairs the result. Parameters ---------- f : callable A function that accepts a sequence and returns a sequence plist: A sequence of pairs Returns ------- qlist : sequence Equivalent to (tuple(f(p)) for p in plist)
f14397:c0:m5
def int_pairs(self, plist):
return self.__pair_repack(self.ints, plist)<EOL>
Translates a sequence of pairs of chimera_index tuples into a a sequence of pairs of linear_index ints. Parameters ---------- plist: A sequence of pairs of tuples Returns ------- qlist : sequence Equivalent to (tuple(self.ints(p)) for p in plist)
f14397:c0:m6
def tuple_pairs(self, plist):
return self.__pair_repack(self.tuples, plist)<EOL>
Translates a sequence of pairs of chimera_index tuples into a a sequence of pairs of linear_index ints. Parameters ---------- plist: A sequence of pairs of tuples Returns ------- qlist : sequence Equivalent to (tuple(self.tuples(p)) for p in plist)
f14397:c0:m7
def pegasus_graph(m, create_using=None, node_list=None, edge_list=None, data=True,<EOL>offset_lists=None, offsets_index=None, coordinates=False, fabric_only=True,<EOL>nice_coordinates=False):
if offset_lists is None:<EOL><INDENT>offsets_descriptor = offsets_index = offsets_index or <NUM_LIT:0><EOL>offset_lists = [<EOL>[(<NUM_LIT:2>, <NUM_LIT:2>, <NUM_LIT:2>, <NUM_LIT:2>, <NUM_LIT:10>, <NUM_LIT:10>, <NUM_LIT:10>, <NUM_LIT:10>, <NUM_LIT:6>, <NUM_LIT:6>, <NUM_LIT:6>, <NUM_LIT:6>,), (<NUM_LIT:6>, <NUM_LIT:6>, <NUM_LIT:6>, <NUM_LIT:6>, <NUM_LIT:2>, <NUM_LIT:2>, <NUM_LIT:2>, <NUM_LIT:2>, <NUM_LIT:10>, <NUM_LIT:10>, <NUM_LIT:10>, <NUM_LIT:10>,)],<EOL>[(<NUM_LIT:2>, <NUM_LIT:2>, <NUM_LIT:2>, <NUM_LIT:2>, <NUM_LIT:10>, <NUM_LIT:10>, <NUM_LIT:10>, <NUM_LIT:10>, <NUM_LIT:6>, <NUM_LIT:6>, <NUM_LIT:6>, <NUM_LIT:6>,), (<NUM_LIT:2>, <NUM_LIT:2>, <NUM_LIT:2>, <NUM_LIT:2>, <NUM_LIT:10>, <NUM_LIT:10>, <NUM_LIT:10>, <NUM_LIT:10>, <NUM_LIT:6>, <NUM_LIT:6>, <NUM_LIT:6>, <NUM_LIT:6>,)],<EOL>[(<NUM_LIT:2>, <NUM_LIT:2>, <NUM_LIT:2>, <NUM_LIT:2>, <NUM_LIT:10>, <NUM_LIT:10>, <NUM_LIT:10>, <NUM_LIT:10>, <NUM_LIT:6>, <NUM_LIT:6>, <NUM_LIT:6>, <NUM_LIT:6>,), (<NUM_LIT:10>, <NUM_LIT:10>, <NUM_LIT:10>, <NUM_LIT:10>, <NUM_LIT:6>, <NUM_LIT:6>, <NUM_LIT:6>, <NUM_LIT:6>, <NUM_LIT:2>, <NUM_LIT:2>, <NUM_LIT:2>, <NUM_LIT:2>,)],<EOL>[(<NUM_LIT:10>, <NUM_LIT:10>, <NUM_LIT:10>, <NUM_LIT:10>, <NUM_LIT:6>, <NUM_LIT:6>, <NUM_LIT:6>, <NUM_LIT:6>, <NUM_LIT:2>, <NUM_LIT:2>, <NUM_LIT:2>, <NUM_LIT:2>,), (<NUM_LIT:10>, <NUM_LIT:10>, <NUM_LIT:10>, <NUM_LIT:10>, <NUM_LIT:6>, <NUM_LIT:6>, <NUM_LIT:6>, <NUM_LIT:6>, <NUM_LIT:2>, <NUM_LIT:2>, <NUM_LIT:2>, <NUM_LIT:2>,)],<EOL>[(<NUM_LIT:10>, <NUM_LIT:10>, <NUM_LIT:10>, <NUM_LIT:10>, <NUM_LIT:6>, <NUM_LIT:6>, <NUM_LIT:6>, <NUM_LIT:6>, <NUM_LIT:2>, <NUM_LIT:2>, <NUM_LIT:2>, <NUM_LIT:2>,), (<NUM_LIT:2>, <NUM_LIT:2>, <NUM_LIT:2>, <NUM_LIT:2>, <NUM_LIT:6>, <NUM_LIT:6>, <NUM_LIT:6>, <NUM_LIT:6>, <NUM_LIT:10>, <NUM_LIT:10>, <NUM_LIT:10>, <NUM_LIT:10>,)],<EOL>[(<NUM_LIT:6>, <NUM_LIT:6>, <NUM_LIT:2>, <NUM_LIT:2>, <NUM_LIT:2>, <NUM_LIT:2>, <NUM_LIT:10>, <NUM_LIT:10>, <NUM_LIT:10>, <NUM_LIT:10>, <NUM_LIT:6>, <NUM_LIT:6>,), (<NUM_LIT:6>, <NUM_LIT:6>, <NUM_LIT:2>, <NUM_LIT:2>, <NUM_LIT:2>, <NUM_LIT:2>, <NUM_LIT:10>, <NUM_LIT:10>, <NUM_LIT:10>, <NUM_LIT:10>, <NUM_LIT:6>, <NUM_LIT:6>,)],<EOL>[(<NUM_LIT:6>, <NUM_LIT:6>, <NUM_LIT:2>, <NUM_LIT:2>, <NUM_LIT:2>, <NUM_LIT:2>, <NUM_LIT:10>, <NUM_LIT:10>, <NUM_LIT:10>, <NUM_LIT:10>, <NUM_LIT:6>, <NUM_LIT:6>,), (<NUM_LIT:6>, <NUM_LIT:6>, <NUM_LIT:10>, <NUM_LIT:10>, <NUM_LIT:10>, <NUM_LIT:10>, <NUM_LIT:2>, <NUM_LIT:2>, <NUM_LIT:2>, <NUM_LIT:2>, <NUM_LIT:6>, <NUM_LIT:6>,)],<EOL>[(<NUM_LIT:6>, <NUM_LIT:6>, <NUM_LIT:6>, <NUM_LIT:6>, <NUM_LIT:6>, <NUM_LIT:6>, <NUM_LIT:6>, <NUM_LIT:6>, <NUM_LIT:6>, <NUM_LIT:6>, <NUM_LIT:6>, <NUM_LIT:6>,), (<NUM_LIT:6>, <NUM_LIT:6>, <NUM_LIT:6>, <NUM_LIT:6>, <NUM_LIT:6>, <NUM_LIT:6>, <NUM_LIT:6>, <NUM_LIT:6>, <NUM_LIT:6>, <NUM_LIT:6>, <NUM_LIT:6>, <NUM_LIT:6>,)],<EOL>][offsets_index]<EOL><DEDENT>elif offsets_index is not None:<EOL><INDENT>raise DWaveNetworkXException("<STR_LIT>")<EOL><DEDENT>else:<EOL><INDENT>for ori in <NUM_LIT:0>, <NUM_LIT:1>:<EOL><INDENT>for x, y in zip(offset_lists[ori][::<NUM_LIT:2>], offset_lists[ori][<NUM_LIT:1>::<NUM_LIT:2>]):<EOL><INDENT>if x != y:<EOL><INDENT>warnings.warn("<STR_LIT>")<EOL><DEDENT><DEDENT><DEDENT>offsets_descriptor = offset_lists<EOL><DEDENT>G = nx.empty_graph(<NUM_LIT:0>, create_using)<EOL>G.name = "<STR_LIT>" % (m, offsets_descriptor)<EOL>m1 = m - <NUM_LIT:1><EOL>if nice_coordinates:<EOL><INDENT>if offsets_index != <NUM_LIT:0>:<EOL><INDENT>raise NotImplementedError("<STR_LIT>")<EOL><DEDENT>labels = '<STR_LIT>'<EOL>c2i = get_pegasus_to_nice_fn()<EOL><DEDENT>elif coordinates:<EOL><INDENT>c2i = lambda *q: q<EOL>labels = '<STR_LIT>'<EOL><DEDENT>else:<EOL><INDENT>labels = '<STR_LIT:int>'<EOL>def c2i(u, w, k, z): return u * <NUM_LIT:12> * m * m1 + w * <NUM_LIT:12> * m1 + k * m1 + z<EOL><DEDENT>construction = (("<STR_LIT>", "<STR_LIT>"), ("<STR_LIT>", m), ("<STR_LIT>", m),<EOL>("<STR_LIT>", <NUM_LIT:12>), ("<STR_LIT>", offset_lists[<NUM_LIT:0>]),<EOL>("<STR_LIT>", offset_lists[<NUM_LIT:1>]), ("<STR_LIT:data>", data),<EOL>("<STR_LIT>", labels))<EOL>G.graph.update(construction)<EOL>max_size = m * (m - <NUM_LIT:1>) * <NUM_LIT> <EOL>if edge_list is None:<EOL><INDENT>if nice_coordinates:<EOL><INDENT>fabric_start = <NUM_LIT:4>,<NUM_LIT:8><EOL>fabric_end = <NUM_LIT:8>, <NUM_LIT:4><EOL><DEDENT>elif fabric_only:<EOL><INDENT>fabric_start = min(s for s in offset_lists[<NUM_LIT:1>]), min(s for s in offset_lists[<NUM_LIT:0>])<EOL>fabric_end = <NUM_LIT:12> - max(s for s in offset_lists[<NUM_LIT:1>]), <NUM_LIT:12> - max(s for s in offset_lists[<NUM_LIT:0>])<EOL><DEDENT>else:<EOL><INDENT>fabric_end = fabric_start = <NUM_LIT:0>, <NUM_LIT:0><EOL><DEDENT>G.add_edges_from((c2i(u, w, k, z), c2i(u, w, k, z + <NUM_LIT:1>))<EOL>for u in (<NUM_LIT:0>, <NUM_LIT:1>)<EOL>for w in range(m)<EOL>for k in range(fabric_start[u] if w == <NUM_LIT:0> else <NUM_LIT:0>, <NUM_LIT:12> - (fabric_end[u] if w == m1 else <NUM_LIT:0>))<EOL>for z in range(m1 - <NUM_LIT:1>))<EOL>G.add_edges_from((c2i(u, w, k, z), c2i(u, w, k + <NUM_LIT:1>, z))<EOL>for u in (<NUM_LIT:0>, <NUM_LIT:1>)<EOL>for w in range(m)<EOL>for k in range(fabric_start[u] if w == <NUM_LIT:0> else <NUM_LIT:0>, <NUM_LIT:12> - (fabric_end[u] if w == m1 else <NUM_LIT:0>), <NUM_LIT:2>)<EOL>for z in range(m1))<EOL>off0, off1 = offset_lists<EOL>def qfilter(u, w, k, z):<EOL><INDENT>if w == <NUM_LIT:0>: return k >= fabric_start[u]<EOL>if w == m1: return k < <NUM_LIT:12>-fabric_end[u]<EOL>return True<EOL><DEDENT>def efilter(e): return qfilter(*e[<NUM_LIT:0>]) and qfilter(*e[<NUM_LIT:1>])<EOL>internal_couplers = (((<NUM_LIT:0>, w, k, z), (<NUM_LIT:1>, z + (kk < off0[k]), kk, w - (k < off1[kk])))<EOL>for w in range(m)<EOL>for kk in range(<NUM_LIT:12>)<EOL>for k in range(<NUM_LIT:0> if w else off1[kk], <NUM_LIT:12> if w < m1 else off1[kk])<EOL>for z in range(m1))<EOL>G.add_edges_from((c2i(*e[<NUM_LIT:0>]), c2i(*e[<NUM_LIT:1>])) for e in internal_couplers if efilter(e))<EOL><DEDENT>else:<EOL><INDENT>G.add_edges_from(edge_list)<EOL><DEDENT>if node_list is not None:<EOL><INDENT>nodes = set(node_list)<EOL>G.remove_nodes_from(set(G) - nodes)<EOL>G.add_nodes_from(nodes) <EOL><DEDENT>if data:<EOL><INDENT>v = <NUM_LIT:0><EOL>for u in range(<NUM_LIT:2>):<EOL><INDENT>for w in range(m):<EOL><INDENT>for k in range(<NUM_LIT:12>):<EOL><INDENT>for z in range(m1):<EOL><INDENT>q = u, w, k, z<EOL>if nice_coordinates:<EOL><INDENT>p = c2i(*q)<EOL>if p in G:<EOL><INDENT>G.node[p]['<STR_LIT>'] = v<EOL>G.node[p]['<STR_LIT>'] = q<EOL><DEDENT><DEDENT>elif coordinates:<EOL><INDENT>if q in G:<EOL><INDENT>G.node[q]['<STR_LIT>'] = v<EOL><DEDENT><DEDENT>else:<EOL><INDENT>if v in G:<EOL><INDENT>G.node[v]['<STR_LIT>'] = q<EOL><DEDENT><DEDENT>v += <NUM_LIT:1><EOL><DEDENT><DEDENT><DEDENT><DEDENT><DEDENT>return G<EOL>
Creates a Pegasus graph with size parameter m. The number of nodes and edges varies according to multiple parameters, for example, pegasus_graph(1) contains zero nodes, pegasus_graph(m, fabric_only=False) contains :math:`24m(m-1)` nodes, pegasus_graph(m, fabric_only=True) contains :math:`24m(m-1)-8m` nodes, and pegasus_graph(m, nice_coordinates=True) contains :math:`24(m-1)^2` nodes. The maximum degree of these graph is 15, and counting formulas are more complicated for edges given most parameter settings. Upper bounds are given below, pegasus_graph(1, fabric_only=False) has zero edges, pegasus_graph(m, fabric_only=False) has :math:`12*(15*(m-1)^2 + m - 3)` edges if m > 1 Note that the above are valid with default offset parameters. A Pegasus lattice is a graph minor of a lattice similar to Chimera, where unit tiles are completely connected. In the most generality, prelattice :math:`Q(N0,N1)` contains nodes of the form :math:`(i, j, 0, k)` with :math:`0 <= k < 2` [vertical nodes] and :math:`(i, j, 1, k)` with :math:`0 <= k < 2` [horizontal nodes] for :math:`0 <= i <= N0` and :math:`0 <= j < N1`; and edges of the form :math:`(i, j, u, k)` ~ :math:`(i+u, j+1-u, u, k)` [external edges] :math:`(i, j, 0, k)` ~ :math:`(i, j, 1, k)` [internal edges] :math:`(i, j, u, 0)` ~ :math:`(i, j, u, 1)` [odd edges] The minor is specified by two lists of offsets; :math:`S0` and :math:`S1` of length :math:`L0` and :math:`L1` (where :math:`L0` and :math:`L1`, and the entries of :math:`S0` and :math:`S1`, must be divisible by 2). From these offsets, we construct our minor, a Pegasus lattice, by contracting the complete intervals of external edges:: I(0, w, k, z) = [(L1*w + k, L0*z + S0[k] + r, 0, k % 2) for 0 <= r < L0] I(1, w, k, z) = [(L1*z + S1[k] + r, L0*w + k, 1, k % 2) for 0 <= r < L1] and deleting the prelattice nodes of any interval not fully contained in :math:`Q(N0, N1)`. This generator is specialized to :math:`L0 = L1 = 12`; :math:`N0 = N1 = 12m`. The notation :math:`(u, w, k, z)` is called the Pegasus index of a node in a Pegasus lattice. The entries can be interpreted as following, :math:`u`: qubit orientation (0 = vertical, 1 = horizontal) :math:`w`: orthogonal major offset :math:`k`: orthogonal minor offset :math:`z`: parallel offset and the edges in the minor have the form :math:`(u, w, k, z)` ~ :math:`(u, w, k, z+1)` [external edges] :math:`(0, w0, k0, z0)` ~ :math:`(1, w1, k1, z1)` [internal edges, see below] :math:`(u, w, 2k, z)` ~ :math:`(u, w, 2k+1, z)` [odd edges] where internal edges only exist when:: w1 = z0 + (1 if k1 < S0[k0] else 0), and z1 = w0 - (1 if k0 < S1[k1] else 0) linear indices are computed from pegasus indices by the formula:: q = ((u * m + w) * 12 + k) * (m - 1) + z Parameters ---------- m : int The size parameter for the Pegasus lattice. create_using : Graph, optional (default None) If provided, this graph is cleared of nodes and edges and filled with the new graph. Usually used to set the type of the graph. node_list : iterable, optional (default None) Iterable of nodes in the graph. If None, calculated from m. Note that this list is used to remove nodes, so any nodes specified not in range(24 * m * (m-1)) will not be added. edge_list : iterable, optional (default None) Iterable of edges in the graph. If None, edges are generated as described above. The nodes in each edge must be integer-labeled in range(24 * m * (m-1)). data : bool, optional (default True) If True, each node has a pegasus_index attribute. The attribute is a 4-tuple Pegasus index as defined above. (if coordinates = True, we set a linear_index, which is an integer) coordinates : bool, optional (default False) If True, node labels are 4-tuple Pegasus indices. Ignored if nice_coordinates is True offset_lists : pair of lists, optional (default None) Used to directly control the offsets, each list in the pair should have length 12, and contain even ints. If offset_lists is not None, then offsets_index must be None. offsets_index : int, optional (default None) A number between 0 and 7 inclusive, to select a preconfigured set of topological parameters. If both offsets_index and offset_lists are None, then we set offsets_index = 0. At least one of these two parameters must be None. fabric_only: bool, optional (default True) The Pegasus graph, by definition, will have some disconnected components. If this True, we will only construct nodes from the largest component. Otherwise, the full disconnected graph will be constructed. Ignored if edge_lists is not None or nice_coordinates is True nice_coordinates: bool, optional (default False) In the case that offsets_index = 0, generate the graph with a nicer coordinate system which is more compatible with Chimera addressing. These coordinates are 5-tuples taking the form (t, y, x, u, k) where 0 <= x < M-1, 0 <= y < M-1, 0 <= u < 2, 0 <= k < 4 and 0 <= t < 3. For any given 0 <= t0 < 3, the subgraph of nodes with t = t0 has the structure of chimera(M-1, M-1, 4) with the addition of odd couplers. Supercedes both the fabric_only and coordinates parameters.
f14399:m0
def pegasus_elimination_order(n, coordinates=False):
m = n<EOL>l = <NUM_LIT:12><EOL>h_order = [<NUM_LIT:4>, <NUM_LIT:5>, <NUM_LIT:6>, <NUM_LIT:7>, <NUM_LIT:0>, <NUM_LIT:1>, <NUM_LIT:2>, <NUM_LIT:3>, <NUM_LIT:8>, <NUM_LIT:9>, <NUM_LIT:10>, <NUM_LIT:11>]<EOL>order = []<EOL>for n_i in range(n): <EOL><INDENT>for l_i in range(<NUM_LIT:0>, l, <NUM_LIT:2>):<EOL><INDENT>for l_v in range(l_i, l_i + <NUM_LIT:2>):<EOL><INDENT>for m_i in range(m - <NUM_LIT:1>): <EOL><INDENT>order.append((<NUM_LIT:0>, n_i, l_v, m_i))<EOL><DEDENT><DEDENT>if n_i > <NUM_LIT:0> and not(l_i % <NUM_LIT:4>):<EOL><INDENT>for m_i in range(m):<EOL><INDENT>for l_h in range(h_order[l_i], h_order[l_i] + <NUM_LIT:4>):<EOL><INDENT>order.append((<NUM_LIT:1>, m_i, l_h, n_i - <NUM_LIT:1>))<EOL><DEDENT><DEDENT><DEDENT><DEDENT><DEDENT>if coordinates:<EOL><INDENT>return order<EOL><DEDENT>else:<EOL><INDENT>return pegasus_coordinates(n).ints(order)<EOL><DEDENT>
Produces a variable elimination order for a pegasus P(n) graph, which provides an upper bound on the treewidth. Simple pegasus variable elimination order rules: - eliminate vertical qubits, one column at a time - eliminate horizontal qubits in each column once their adjacent vertical qubits have been eliminated Many other orderings are possible giving the same treewidth upper bound of 12n-4 for a P(n) see pegasus_var_order_extra.py for a few. P(n) contains cliques of size 12n-10 so we know the treewidth of P(n) is in [12n-11,12n-4]. the treewidth bound generated by a variable elimination order can be verified using dwave_networkx.elimination_order_width. Example: import dwave_networkx as dwnx n = 6 P = dwnx.generators.pegasus_graph(n) order = pegasus_var_order(n) print(dwnx.elimination_order_width(P,order))
f14399:m1
def get_tuple_fragmentation_fn(pegasus_graph):
horizontal_offsets = pegasus_graph.graph['<STR_LIT>']<EOL>vertical_offsets = pegasus_graph.graph['<STR_LIT>']<EOL>def fragment_tuple(pegasus_coords):<EOL><INDENT>fragments = []<EOL>for u, w, k, z in pegasus_coords:<EOL><INDENT>offset = horizontal_offsets if u else vertical_offsets<EOL>offset = offset[k]<EOL>x0 = (z * <NUM_LIT:12> + offset) // <NUM_LIT:2><EOL>y = (w * <NUM_LIT:12> + k) // <NUM_LIT:2><EOL>r = k % <NUM_LIT:2><EOL>base = [<NUM_LIT:0>, <NUM_LIT:0>, u, r]<EOL>for x in range(x0, x0 + <NUM_LIT:6>):<EOL><INDENT>base[u] = x<EOL>base[<NUM_LIT:1> - u] = y<EOL>fragments.append(tuple(base))<EOL><DEDENT><DEDENT>return fragments<EOL><DEDENT>return fragment_tuple<EOL>
Returns a fragmentation function that is specific to pegasus_graph. This fragmentation function, fragment_tuple(..), takes in a list of Pegasus qubit coordinates and returns their corresponding K2,2 Chimera fragment coordinates. Details on the returned function, fragment_tuple(list_of_pegasus_coordinates): Each Pegasus qubit is split into six fragments. If edges are drawn between adjacent fragments and drawn between fragments that are connected by an existing Pegasus coupler, we can see that a K2,2 Chimera graph is formed. The K2,2 Chimera graph uses a coordinate system with an origin at the upper left corner of the graph. y: number of vertical fragments from the top-most row x: number of horizontal fragments from the left-most column u: 1 if it belongs to a horizontal qubit, 0 otherwise r: fragment index on the K2,2 shore Parameters ---------- pegasus_graph: networkx.graph A pegasus graph Returns ------- fragment_tuple(pegasus_coordinates): a function A function that accepts a list of pegasus coordinates and returns a list of their corresponding K2,2 Chimera coordinates.
f14399:m2
def get_tuple_defragmentation_fn(pegasus_graph):
horizontal_offsets = pegasus_graph.graph['<STR_LIT>']<EOL>vertical_offsets = pegasus_graph.graph['<STR_LIT>']<EOL>def defragment_tuple(chimera_coords):<EOL><INDENT>pegasus_coords = []<EOL>for y, x, u, r in chimera_coords:<EOL><INDENT>shifts = [x, y]<EOL>offsets = horizontal_offsets if u else vertical_offsets<EOL>w, k = divmod(<NUM_LIT:2> * shifts[u] + r, <NUM_LIT:12>)<EOL>x0 = shifts[<NUM_LIT:1>-u] * <NUM_LIT:2> - offsets[k]<EOL>z = x0 // <NUM_LIT:12><EOL>pegasus_coords.append((u, w, k, z))<EOL><DEDENT>return list(set(pegasus_coords))<EOL><DEDENT>return defragment_tuple<EOL>
Returns a de-fragmentation function that is specific to pegasus_graph. The returned de-fragmentation function, defragment_tuple(..), takes in a list of K2,2 Chimera coordinates and returns the corresponding list of unique pegasus coordinates. Details on the returned function, defragment_tuple(list_of_chimera_fragment_coordinates): Each Pegasus qubit is split into six fragments. If edges are drawn between adjacent fragments and drawn between fragments that are connected by an existing Pegasus coupler, we can see that a K2,2 Chimera graph is formed. The K2,2 Chimera graph uses a coordinate system with an origin at the upper left corner of the graph. y: number of vertical fragments from the top-most row x: number of horizontal fragments from the left-most column u: 1 if it belongs to a horizontal qubit, 0 otherwise r: fragment index on the K2,2 shore The defragment_tuple(..) takes in the list of Chimera fragments and returns a list of their corresponding Pegasus qubit coordinates. Note that the returned list has a unique set of Pegasus coordinates. Parameters ---------- pegasus_graph: networkx.graph A Pegasus graph Returns ------- defragment_tuple(chimera_coordinates): a function A function that accepts a list of chimera coordinates and returns a set of their corresponding Pegasus coordinates.
f14399:m3
def get_pegasus_to_nice_fn(*args, **kwargs):
if args or kwargs:<EOL><INDENT>warnings.warn("<STR_LIT>")<EOL><DEDENT>def p2n0(u, w, k, z): return (<NUM_LIT:0>, w-<NUM_LIT:1> if u else z, z if u else w, u, k-<NUM_LIT:4> if u else k-<NUM_LIT:4>)<EOL>def p2n1(u, w, k, z): return (<NUM_LIT:1>, w-<NUM_LIT:1> if u else z, z if u else w, u, k if u else k-<NUM_LIT:8>)<EOL>def p2n2(u, w, k, z): return (<NUM_LIT:2>, w if u else z, z if u else w-<NUM_LIT:1>, u, k-<NUM_LIT:8> if u else k)<EOL>def p2n(u, w, k, z): return [p2n0, p2n1, p2n2][(<NUM_LIT:2>-u-(<NUM_LIT:2>*u-<NUM_LIT:1>)*(k//<NUM_LIT:4>)) % <NUM_LIT:3>](u, w, k, z)<EOL>return p2n<EOL>
Returns a coordinate translation function from the 4-term pegasus_index coordinates to the 5-term "nice" coordinates. Details on the returned function, pegasus_to_nice(u,w,k,z) Inputs are 4-tuples of ints, return is a 5-tuple of ints. See pegasus_graph for description of the pegasus_index and "nice" coordinate systems. Returns ------- pegasus_to_nice_fn(chimera_coordinates): a function A function that accepts augmented chimera coordinates and returns corresponding Pegasus coordinates.
f14399:m4
def get_nice_to_pegasus_fn(*args, **kwargs):
if args or kwargs:<EOL><INDENT>warnings.warn("<STR_LIT>")<EOL><DEDENT>def c2p0(y, x, u, k): return (u, y+<NUM_LIT:1> if u else x, <NUM_LIT:4>+k if u else <NUM_LIT:4>+k, x if u else y)<EOL>def c2p1(y, x, u, k): return (u, y+<NUM_LIT:1> if u else x, k if u else <NUM_LIT:8>+k, x if u else y)<EOL>def c2p2(y, x, u, k): return (u, y if u else x + <NUM_LIT:1>, <NUM_LIT:8>+k if u else k, x if u else y)<EOL>def n2p(t, y, x, u, k): return [c2p0, c2p1, c2p2][t](y, x, u, k)<EOL>return n2p<EOL>
Returns a coordinate translation function from the 5-term "nice" coordinates to the 4-term pegasus_index coordinates. Details on the returned function, nice_to_pegasus(t, y, x, u, k) Inputs are 5-tuples of ints, return is a 4-tuple of ints. See pegasus_graph for description of the pegasus_index and "nice" coordinate systems. Returns ------- nice_to_pegasus_fn(pegasus_coordinates): a function A function that accepts Pegasus coordinates and returns the corresponding augmented chimera coordinates
f14399:m5
def __init__(self, m):
self.args = m, m - <NUM_LIT:1><EOL>
Provides coordinate converters for the pegasus indexing scheme. Parameters ---------- m : int The size parameter for the Pegasus lattice.
f14399:c0:m0
def int(self, q):
u, w, k, z = q<EOL>m, m1 = self.args<EOL>return ((m * u + w) * <NUM_LIT:12> + k) * m1 + z<EOL>
Converts the chimera_index `q` into an linear_index Parameters ---------- q : tuple The chimera_index node label Returns ------- r : int The linear_index node label corresponding to q
f14399:c0:m1
def tuple(self, r):
m, m1 = self.args<EOL>r, z = divmod(r, m1)<EOL>r, k = divmod(r, <NUM_LIT:12>)<EOL>u, w = divmod(r, m)<EOL>return u, w, k, z<EOL>
Converts the linear_index `q` into an pegasus_index Parameters ---------- r : int The linear_index node label Returns ------- q : tuple The pegasus_index node label corresponding to r
f14399:c0:m2
def ints(self, qlist):
m, m1 = self.args<EOL>return (((m * u + w) * <NUM_LIT:12> + k) * m1 + z for (u, w, k, z) in qlist)<EOL>
Converts a sequence of pegasus_index node labels into linear_index node labels, preserving order Parameters ---------- qlist : sequence of ints The pegasus_index node labels Returns ------- rlist : iterable of tuples The linear_lindex node lables corresponding to qlist
f14399:c0:m3
def tuples(self, rlist):
m, m1 = self.args<EOL>for r in rlist:<EOL><INDENT>r, z = divmod(r, m1)<EOL>r, k = divmod(r, <NUM_LIT:12>)<EOL>u, w = divmod(r, m)<EOL>yield u, w, k, z<EOL><DEDENT>
Converts a sequence of linear_index node labels into pegasus_index node labels, preserving order Parameters ---------- rlist : sequence of tuples The linear_index node labels Returns ------- qlist : iterable of ints The pegasus_index node lables corresponding to rlist
f14399:c0:m4
def __pair_repack(self, f, plist):
ulist = f(u for p in plist for u in p)<EOL>for u in ulist:<EOL><INDENT>v = next(ulist)<EOL>yield u, v<EOL><DEDENT>
Flattens a sequence of pairs to pass through `f`, and then re-pairs the result. Parameters ---------- f : callable A function that accepts a sequence and returns a sequence plist: A sequence of pairs Returns ------- qlist : sequence Equivalent to (tuple(f(p)) for p in plist)
f14399:c0:m5
def int_pairs(self, plist):
return self.__pair_repack(self.ints, plist)<EOL>
Translates a sequence of pairs of chimera_index tuples into a a sequence of pairs of linear_index ints. Parameters ---------- plist: A sequence of pairs of tuples Returns ------- qlist : sequence Equivalent to (tuple(self.ints(p)) for p in plist)
f14399:c0:m6
def tuple_pairs(self, plist):
return self.__pair_repack(self.tuples, plist)<EOL>
Translates a sequence of pairs of chimera_index tuples into a a sequence of pairs of linear_index ints. Parameters ---------- plist: A sequence of pairs of tuples Returns ------- qlist : sequence Equivalent to (tuple(self.tuples(p)) for p in plist)
f14399:c0:m7
def draw_qubit_graph(G, layout, linear_biases={}, quadratic_biases={},<EOL>nodelist=None, edgelist=None, cmap=None, edge_cmap=None, vmin=None, vmax=None,<EOL>edge_vmin=None, edge_vmax=None,<EOL>**kwargs):
if linear_biases or quadratic_biases:<EOL><INDENT>try:<EOL><INDENT>import matplotlib.pyplot as plt<EOL>import matplotlib as mpl<EOL><DEDENT>except ImportError:<EOL><INDENT>raise ImportError("<STR_LIT>")<EOL><DEDENT>if nodelist is None:<EOL><INDENT>nodelist = G.nodes()<EOL><DEDENT>if edgelist is None:<EOL><INDENT>edgelist = G.edges()<EOL><DEDENT>if cmap is None:<EOL><INDENT>cmap = plt.get_cmap('<STR_LIT>')<EOL><DEDENT>if edge_cmap is None:<EOL><INDENT>edge_cmap = plt.get_cmap('<STR_LIT>')<EOL><DEDENT>def edge_color(u, v):<EOL><INDENT>c = <NUM_LIT:0.><EOL>if (u, v) in quadratic_biases:<EOL><INDENT>c += quadratic_biases[(u, v)]<EOL><DEDENT>if (v, u) in quadratic_biases:<EOL><INDENT>c += quadratic_biases[(v, u)]<EOL><DEDENT>return c<EOL><DEDENT>def node_color(v):<EOL><INDENT>c = <NUM_LIT:0.><EOL>if v in linear_biases:<EOL><INDENT>c += linear_biases[v]<EOL><DEDENT>if (v, v) in quadratic_biases:<EOL><INDENT>c += quadratic_biases[(v, v)]<EOL><DEDENT>return c<EOL><DEDENT>node_color = [node_color(v) for v in nodelist]<EOL>edge_color = [edge_color(u, v) for u, v in edgelist]<EOL>kwargs['<STR_LIT>'] = edge_color<EOL>kwargs['<STR_LIT>'] = node_color<EOL>vmag = max(max(abs(c) for c in node_color), max(abs(c) for c in edge_color))<EOL>if vmin is None:<EOL><INDENT>vmin = -<NUM_LIT:1> * vmag<EOL><DEDENT>if vmax is None:<EOL><INDENT>vmax = vmag<EOL><DEDENT>if edge_vmin is None:<EOL><INDENT>edge_vmin = -<NUM_LIT:1> * vmag<EOL><DEDENT>if edge_vmax is None:<EOL><INDENT>edge_vmax = vmag<EOL><DEDENT><DEDENT>draw(G, layout, nodelist=nodelist, edgelist=edgelist,<EOL>cmap=cmap, edge_cmap=edge_cmap, vmin=vmin, vmax=vmax, edge_vmin=edge_vmin,<EOL>edge_vmax=edge_vmax,<EOL>**kwargs)<EOL>if linear_biases or quadratic_biases:<EOL><INDENT>fig = plt.figure(<NUM_LIT:1>)<EOL>cax = fig.add_axes([<NUM_LIT>, <NUM_LIT>, <NUM_LIT>, <NUM_LIT>]) <EOL>mpl.colorbar.ColorbarBase(cax, cmap=cmap,<EOL>norm=mpl.colors.Normalize(vmin=-<NUM_LIT:1> * vmag, vmax=vmag, clip=False),<EOL>orientation='<STR_LIT>')<EOL><DEDENT>
Draws graph G according to layout. If `linear_biases` and/or `quadratic_biases` are provided, these are visualized on the plot. Parameters ---------- G : NetworkX graph The graph to be drawn layout : dict A dict of coordinates associated with each node in G. Should be of the form {node: coordinate, ...}. Coordinates will be treated as vectors, and should all have the same length. linear_biases : dict (optional, default {}) A dict of biases associated with each node in G. Should be of form {node: bias, ...}. Each bias should be numeric. quadratic_biases : dict (optional, default {}) A dict of biases associated with each edge in G. Should be of form {edge: bias, ...}. Each bias should be numeric. Self-loop edges (i.e., :math:`i=j`) are treated as linear biases. kwargs : optional keywords See networkx.draw_networkx() for a description of optional keywords, with the exception of the `pos` parameter which is not used by this function. If `linear_biases` or `quadratic_biases` are provided, any provided `node_color` or `edge_color` arguments are ignored.
f14402:m0
def draw_embedding(G, layout, emb, embedded_graph=None, interaction_edges=None,<EOL>chain_color=None, unused_color=(<NUM_LIT>,<NUM_LIT>,<NUM_LIT>,<NUM_LIT:1.0>), cmap=None,<EOL>show_labels=False, **kwargs):
try:<EOL><INDENT>import matplotlib.pyplot as plt<EOL>import matplotlib as mpl<EOL><DEDENT>except ImportError:<EOL><INDENT>raise ImportError("<STR_LIT>")<EOL><DEDENT>if nx.utils.is_string_like(unused_color):<EOL><INDENT>from matplotlib.colors import colorConverter<EOL>alpha = kwargs.get('<STR_LIT>',<NUM_LIT:1.0>)<EOL>unused_color = colorConverter.to_rgba(unused_color,alpha)<EOL><DEDENT>if chain_color is None:<EOL><INDENT>import matplotlib.cm<EOL>n = max(<NUM_LIT:1.>, len(emb) - <NUM_LIT:1.>)<EOL>if kwargs.get("<STR_LIT>"):<EOL><INDENT>color = matplotlib.cm.get_cmap(kwargs.get("<STR_LIT>"))<EOL><DEDENT>else:<EOL><INDENT>color = distinguishable_color_map(int(n+<NUM_LIT:1>))<EOL><DEDENT>var_i = {v: i for i, v in enumerate(emb)}<EOL>chain_color = {v: color(i/n) for i, v in enumerate(emb)}<EOL><DEDENT>qlabel = {q: v for v, chain in iteritems(emb) for q in chain}<EOL>edgelist = []<EOL>edge_color = []<EOL>background_edgelist = []<EOL>background_edge_color = []<EOL>if interaction_edges is not None:<EOL><INDENT>interactions = nx.Graph()<EOL>interactions.add_edges_from(interaction_edges)<EOL>def show(p, q, u, v): return interactions.has_edge(p, q)<EOL><DEDENT>elif embedded_graph is not None:<EOL><INDENT>def show(p, q, u, v): return embedded_graph.has_edge(u, v)<EOL><DEDENT>else:<EOL><INDENT>def show(p, q, u, v): return True<EOL><DEDENT>for (p, q) in G.edges():<EOL><INDENT>u = qlabel.get(p)<EOL>v = qlabel.get(q)<EOL>if u is None or v is None:<EOL><INDENT>ec = unused_color<EOL><DEDENT>elif u == v:<EOL><INDENT>ec = chain_color.get(u)<EOL><DEDENT>elif show(p, q, u, v):<EOL><INDENT>ec = (<NUM_LIT:0>, <NUM_LIT:0>, <NUM_LIT:0>, <NUM_LIT:1>)<EOL><DEDENT>else:<EOL><INDENT>ec = unused_color<EOL><DEDENT>if ec == unused_color:<EOL><INDENT>background_edgelist.append((p, q))<EOL>background_edge_color.append(ec)<EOL><DEDENT>elif ec is not None:<EOL><INDENT>edgelist.append((p, q))<EOL>edge_color.append(ec)<EOL><DEDENT><DEDENT>nodelist = []<EOL>node_color = []<EOL>for p in G.nodes():<EOL><INDENT>u = qlabel.get(p)<EOL>if u is None:<EOL><INDENT>pc = unused_color<EOL><DEDENT>else:<EOL><INDENT>pc = chain_color.get(u)<EOL><DEDENT>if pc is not None:<EOL><INDENT>nodelist.append(p)<EOL>node_color.append(pc)<EOL><DEDENT><DEDENT>labels = {}<EOL>if show_labels:<EOL><INDENT>for v in emb.keys():<EOL><INDENT>c = emb[v]<EOL>labels[list(c)[<NUM_LIT:0>]] = str(v)<EOL><DEDENT><DEDENT>if unused_color is not None:<EOL><INDENT>draw(G, layout, nodelist=nodelist, edgelist=background_edgelist,<EOL>node_color=node_color, edge_color=background_edge_color,<EOL>**kwargs)<EOL><DEDENT>draw(G, layout, nodelist=nodelist, edgelist=edgelist,<EOL>node_color=node_color, edge_color=edge_color, labels=labels,<EOL>**kwargs)<EOL>
Draws an embedding onto the graph G, according to layout. If interaction_edges is not None, then only display the couplers in that list. If embedded_graph is not None, the only display the couplers between chains with intended couplings according to embedded_graph. Parameters ---------- G : NetworkX graph The graph to be drawn layout : dict A dict of coordinates associated with each node in G. Should be of the form {node: coordinate, ...}. Coordinates will be treated as vectors, and should all have the same length. emb : dict A dict of chains associated with each node in G. Should be of the form {node: chain, ...}. Chains should be iterables of qubit labels (qubits are nodes in G). embedded_graph : NetworkX graph (optional, default None) A graph which contains all keys of emb as nodes. If specified, edges of G will be considered interactions if and only if they exist between two chains of emb if their keys are connected by an edge in embedded_graph interaction_edges : list (optional, default None) A list of edges which will be used as interactions. show_labels: boolean (optional, default False) If show_labels is True, then each chain in emb is labelled with its key. chain_color : dict (optional, default None) A dict of colors associated with each key in emb. Should be of the form {node: rgba_color, ...}. Colors should be length-4 tuples of floats between 0 and 1 inclusive. If chain_color is None, each chain will be assigned a different color. unused_color : tuple or color string (optional, default (0.9,0.9,0.9,1.0)) The color to use for nodes and edges of G which are not involved in chains, and edges which are neither chain edges nor interactions. If unused_color is None, these nodes and edges will not be shown at all. kwargs : optional keywords See networkx.draw_networkx() for a description of optional keywords, with the exception of the `pos` parameter which is not used by this function. If `linear_biases` or `quadratic_biases` are provided, any provided `node_color` or `edge_color` arguments are ignored.
f14402:m1
def draw_yield(G, layout, perfect_graph, unused_color=(<NUM_LIT>,<NUM_LIT>,<NUM_LIT>,<NUM_LIT:1.0>),<EOL>fault_color=(<NUM_LIT:1.0>,<NUM_LIT:0.0>,<NUM_LIT:0.0>,<NUM_LIT:1.0>), fault_shape='<STR_LIT:x>',<EOL>fault_style='<STR_LIT>', **kwargs):
try:<EOL><INDENT>import matplotlib.pyplot as plt<EOL>import matplotlib as mpl<EOL><DEDENT>except ImportError:<EOL><INDENT>raise ImportError("<STR_LIT>")<EOL><DEDENT>nodelist = G.nodes()<EOL>edgelist = G.edges()<EOL>faults_nodelist = perfect_graph.nodes() - nodelist<EOL>faults_edgelist = perfect_graph.edges() - edgelist<EOL>faults_node_color = [fault_color for v in faults_nodelist]<EOL>faults_edge_color = [fault_color for v in faults_edgelist]<EOL>draw(perfect_graph, layout, nodelist=faults_nodelist, edgelist=faults_edgelist,<EOL>node_color=faults_node_color, edge_color=faults_edge_color,<EOL>style=fault_style, node_shape=fault_shape,<EOL>**kwargs )<EOL>if unused_color is not None:<EOL><INDENT>if nodelist is None:<EOL><INDENT>nodelist = G.nodes() - faults_nodelist<EOL><DEDENT>if edgelist is None:<EOL><INDENT>edgelist = G.edges() - faults_edgelist<EOL><DEDENT>unused_node_color = [unused_color for v in nodelist]<EOL>unused_edge_color = [unused_color for v in edgelist]<EOL>draw(perfect_graph, layout, nodelist=nodelist, edgelist=edgelist,<EOL>node_color=unused_node_color, edge_color=unused_edge_color,<EOL>**kwargs)<EOL><DEDENT>
Draws the given graph G with highlighted faults, according to layout. Parameters ---------- G : NetworkX graph The graph to be parsed for faults layout : dict A dict of coordinates associated with each node in perfect_graph. Should be of the form {node: coordinate, ...}. Coordinates will be treated as vectors, and should all have the same length. perfect_graph : NetworkX graph The graph to be drawn with highlighted faults unused_color : tuple or color string (optional, default (0.9,0.9,0.9,1.0)) The color to use for nodes and edges of G which are not faults. If unused_color is None, these nodes and edges will not be shown at all. fault_color : tuple or color string (optional, default (1.0,0.0,0.0,1.0)) A color to represent nodes absent from the graph G. Colors should be length-4 tuples of floats between 0 and 1 inclusive. fault_shape : string, optional (default='x') The shape of the fault nodes. Specification is as matplotlib.scatter marker, one of 'so^>v<dph8'. fault_style : string, optional (default='dashed') Edge fault line style (solid|dashed|dotted,dashdot) kwargs : optional keywords See networkx.draw_networkx() for a description of optional keywords, with the exception of the `pos` parameter which is not used by this function. If `linear_biases` or `quadratic_biases` are provided, any provided `node_color` or `edge_color` arguments are ignored.
f14402:m2
def pegasus_layout(G, scale=<NUM_LIT:1.>, center=None, dim=<NUM_LIT:2>, crosses=False):
if not isinstance(G, nx.Graph) or G.graph.get("<STR_LIT>") != "<STR_LIT>":<EOL><INDENT>raise ValueError("<STR_LIT>")<EOL><DEDENT>if G.graph.get('<STR_LIT>') == '<STR_LIT>':<EOL><INDENT>m = <NUM_LIT:3>*(G.graph['<STR_LIT>']-<NUM_LIT:1>)<EOL>c_coords = chimera_node_placer_2d(m, m, <NUM_LIT:4>, scale=scale, center=center, dim=dim)<EOL>def xy_coords(t, y, x, u, k): return c_coords(<NUM_LIT:3>*y+<NUM_LIT:2>-t, <NUM_LIT:3>*x+t, u, k)<EOL>pos = {v: xy_coords(*v) for v in G.nodes()}<EOL><DEDENT>else:<EOL><INDENT>xy_coords = pegasus_node_placer_2d(G, scale, center, dim, crosses=crosses)<EOL>if G.graph.get('<STR_LIT>') == '<STR_LIT>':<EOL><INDENT>pos = {v: xy_coords(*v) for v in G.nodes()}<EOL><DEDENT>elif G.graph.get('<STR_LIT:data>'):<EOL><INDENT>pos = {v: xy_coords(*dat['<STR_LIT>']) for v, dat in G.nodes(data=True)}<EOL><DEDENT>else:<EOL><INDENT>m = G.graph.get('<STR_LIT>')<EOL>coord = pegasus_coordinates(m)<EOL>pos = {v: xy_coords(*coord.tuple(v)) for v in G.nodes()}<EOL><DEDENT><DEDENT>return pos<EOL>
Positions the nodes of graph G in a Pegasus topology. NumPy (http://scipy.org) is required for this function. Parameters ---------- G : NetworkX graph Should be a Pegasus graph or a subgraph of a Pegasus graph. This should be the product of dwave_networkx.pegasus_graph scale : float (default 1.) Scale factor. When scale = 1, all positions fit within [0, 1] on the x-axis and [-1, 0] on the y-axis. center : None or array (default None) Coordinates of the top left corner. dim : int (default 2) Number of dimensions. When dim > 2, all extra dimensions are set to 0. crosses: boolean (optional, default False) If crosses is True, K_4,4 subgraphs are shown in a cross rather than L configuration. Ignored if G was defined with nice_coordinates=True. Returns ------- pos : dict A dictionary of positions keyed by node. Examples -------- >>> G = dnx.pegasus_graph(1) >>> pos = dnx.pegasus_layout(G)
f14405:m0
def pegasus_node_placer_2d(G, scale=<NUM_LIT:1.>, center=None, dim=<NUM_LIT:2>, crosses=False):
import numpy as np<EOL>m = G.graph.get('<STR_LIT>')<EOL>h_offsets = G.graph.get("<STR_LIT>")<EOL>v_offsets = G.graph.get("<STR_LIT>")<EOL>tile_width = G.graph.get("<STR_LIT>")<EOL>tile_center = tile_width / <NUM_LIT:2> - <NUM_LIT><EOL>scale /= m * tile_width<EOL>if center is None:<EOL><INDENT>center = np.zeros(dim)<EOL><DEDENT>else:<EOL><INDENT>center = np.asarray(center)<EOL><DEDENT>paddims = dim - <NUM_LIT:2><EOL>if paddims < <NUM_LIT:0>:<EOL><INDENT>raise ValueError("<STR_LIT>")<EOL><DEDENT>if len(center) != dim:<EOL><INDENT>raise ValueError("<STR_LIT>")<EOL><DEDENT>if crosses:<EOL><INDENT>cross_shift = <NUM_LIT><EOL><DEDENT>else:<EOL><INDENT>cross_shift = <NUM_LIT:0.><EOL><DEDENT>def _xy_coords(u, w, k, z):<EOL><INDENT>if k % <NUM_LIT:2>:<EOL><INDENT>p = -<NUM_LIT><EOL><DEDENT>else:<EOL><INDENT>p = <NUM_LIT><EOL><DEDENT>if u:<EOL><INDENT>xy = np.array([z*tile_width+h_offsets[k] + tile_center, -tile_width*w-k-p+cross_shift])<EOL><DEDENT>else:<EOL><INDENT>xy = np.array([tile_width*w+k+p+cross_shift, -z*tile_width-v_offsets[k]-tile_center])<EOL><DEDENT>return np.hstack((xy * scale, np.zeros(paddims))) + center<EOL><DEDENT>return _xy_coords<EOL>
Generates a function that converts Pegasus indices to x, y coordinates for a plot. Parameters ---------- G : NetworkX graph Should be a Pegasus graph or a subgraph of a Pegasus graph. This should be the product of dwave_networkx.pegasus_graph scale : float (default 1.) Scale factor. When scale = 1, all positions fit within [0, 1] on the x-axis and [-1, 0] on the y-axis. center : None or array (default None) Coordinates of the top left corner. dim : int (default 2) Number of dimensions. When dim > 2, all extra dimensions are set to 0. crosses: boolean (optional, default False) If crosses is True, K_4,4 subgraphs are shown in a cross rather than L configuration. Returns ------- xy_coords : function A function that maps a Pegasus index (u, w, k, z) in a Pegasus lattice to x,y coordinates such as used by a plot.
f14405:m1
def draw_pegasus(G, crosses=False, **kwargs):
draw_qubit_graph(G, pegasus_layout(G, crosses=crosses), **kwargs)<EOL>
Draws graph G in a Pegasus topology. If `linear_biases` and/or `quadratic_biases` are provided, these are visualized on the plot. Parameters ---------- G : NetworkX graph Should be a Pegasus graph or a subgraph of a Pegasus graph, a product of dwave_networkx.pegasus_graph. linear_biases : dict (optional, default {}) A dict of biases associated with each node in G. Should be of form {node: bias, ...}. Each bias should be numeric. quadratic_biases : dict (optional, default {}) A dict of biases associated with each edge in G. Should be of form {edge: bias, ...}. Each bias should be numeric. Self-loop edges (i.e., :math:`i=j`) are treated as linear biases. crosses: boolean (optional, default False) If crosses is True, K_4,4 subgraphs are shown in a cross rather than L configuration. Ignored if G was defined with nice_coordinates=True. kwargs : optional keywords See networkx.draw_networkx() for a description of optional keywords, with the exception of the `pos` parameter which is not used by this function. If `linear_biases` or `quadratic_biases` are provided, any provided `node_color` or `edge_color` arguments are ignored. Examples -------- >>> # Plot a Pegasus graph with size parameter 2 >>> import networkx as nx >>> import dwave_networkx as dnx >>> import matplotlib.pyplot as plt >>> G = dnx.pegasus_graph(2) >>> dnx.draw_pegasus(G) >>> plt.show()
f14405:m2
def draw_pegasus_embedding(G, *args, **kwargs):
crosses = kwargs.pop("<STR_LIT>", False)<EOL>draw_embedding(G, pegasus_layout(G, crosses=crosses), *args, **kwargs)<EOL>
Draws an embedding onto the pegasus graph G, according to layout. If interaction_edges is not None, then only display the couplers in that list. If embedded_graph is not None, the only display the couplers between chains with intended couplings according to embedded_graph. Parameters ---------- G : NetworkX graph Should be a Pegasus graph or a subgraph of a Pegasus graph. This should be the product of dwave_networkx.pegasus_graph emb : dict A dict of chains associated with each node in G. Should be of the form {node: chain, ...}. Chains should be iterables of qubit labels (qubits are nodes in G). embedded_graph : NetworkX graph (optional, default None) A graph which contains all keys of emb as nodes. If specified, edges of G will be considered interactions if and only if they exist between two chains of emb if their keys are connected by an edge in embedded_graph interaction_edges : list (optional, default None) A list of edges which will be used as interactions. show_labels: boolean (optional, default False) If show_labels is True, then each chain in emb is labelled with its key. chain_color : dict (optional, default None) A dict of colors associated with each key in emb. Should be of the form {node: rgba_color, ...}. Colors should be length-4 tuples of floats between 0 and 1 inclusive. If chain_color is None, each chain will be assigned a different color. unused_color : tuple (optional, default (0.9,0.9,0.9,1.0)) The color to use for nodes and edges of G which are not involved in chains, and edges which are neither chain edges nor interactions. If unused_color is None, these nodes and edges will not be shown at all. crosses: boolean (optional, default False) If crosses is True, K_4,4 subgraphs are shown in a cross rather than L configuration. Ignored if G was defined with nice_coordinates=True. kwargs : optional keywords See networkx.draw_networkx() for a description of optional keywords, with the exception of the `pos` parameter which is not used by this function. If `linear_biases` or `quadratic_biases` are provided, any provided `node_color` or `edge_color` arguments are ignored.
f14405:m3
def draw_pegasus_yield(G, **kwargs):
try:<EOL><INDENT>assert(G.graph["<STR_LIT>"] == "<STR_LIT>")<EOL>m = G.graph['<STR_LIT>']<EOL>offset_lists = (G.graph['<STR_LIT>'], G.graph['<STR_LIT>'])<EOL>coordinates = G.graph["<STR_LIT>"] == "<STR_LIT>"<EOL><DEDENT>except:<EOL><INDENT>raise ValueError("<STR_LIT>")<EOL><DEDENT>perfect_graph = pegasus_graph(m, offset_lists=offset_lists, coordinates=coordinates)<EOL>draw_yield(G, pegasus_layout(perfect_graph), perfect_graph, **kwargs)<EOL>
Draws the given graph G with highlighted faults, according to layout. Parameters ---------- G : NetworkX graph The graph to be parsed for faults unused_color : tuple or color string (optional, default (0.9,0.9,0.9,1.0)) The color to use for nodes and edges of G which are not faults. If unused_color is None, these nodes and edges will not be shown at all. fault_color : tuple or color string (optional, default (1.0,0.0,0.0,1.0)) A color to represent nodes absent from the graph G. Colors should be length-4 tuples of floats between 0 and 1 inclusive. fault_shape : string, optional (default='x') The shape of the fault nodes. Specification is as matplotlib.scatter marker, one of 'so^>v<dph8'. fault_style : string, optional (default='dashed') Edge fault line style (solid|dashed|dotted,dashdot) kwargs : optional keywords See networkx.draw_networkx() for a description of optional keywords, with the exception of the `pos` parameter which is not used by this function. If `linear_biases` or `quadratic_biases` are provided, any provided `node_color` or `edge_color` arguments are ignored.
f14405:m4
def chimera_layout(G, scale=<NUM_LIT:1.>, center=None, dim=<NUM_LIT:2>):
if not isinstance(G, nx.Graph):<EOL><INDENT>empty_graph = nx.Graph()<EOL>empty_graph.add_edges_from(G)<EOL>G = empty_graph<EOL><DEDENT>if G.graph.get("<STR_LIT>") == "<STR_LIT>":<EOL><INDENT>m = G.graph['<STR_LIT>']<EOL>n = G.graph['<STR_LIT>']<EOL>t = G.graph['<STR_LIT>']<EOL>xy_coords = chimera_node_placer_2d(m, n, t, scale, center, dim)<EOL>if G.graph.get('<STR_LIT>') == '<STR_LIT>':<EOL><INDENT>pos = {v: xy_coords(*v) for v in G.nodes()}<EOL><DEDENT>elif G.graph.get('<STR_LIT:data>'):<EOL><INDENT>pos = {v: xy_coords(*dat['<STR_LIT>']) for v, dat in G.nodes(data=True)}<EOL><DEDENT>else:<EOL><INDENT>coord = chimera_coordinates(m, n, t)<EOL>pos = {v: xy_coords(*coord.tuple(v)) for v in G.nodes()}<EOL><DEDENT><DEDENT>else:<EOL><INDENT>if all('<STR_LIT>' in dat for __, dat in G.nodes(data=True)):<EOL><INDENT>chimera_indices = {v: dat['<STR_LIT>'] for v, dat in G.nodes(data=True)}<EOL><DEDENT>else:<EOL><INDENT>chimera_indices = find_chimera_indices(G)<EOL><DEDENT>m = max(idx[<NUM_LIT:0>] for idx in itervalues(chimera_indices)) + <NUM_LIT:1><EOL>n = max(idx[<NUM_LIT:1>] for idx in itervalues(chimera_indices)) + <NUM_LIT:1><EOL>t = max(idx[<NUM_LIT:3>] for idx in itervalues(chimera_indices)) + <NUM_LIT:1><EOL>xy_coords = chimera_node_placer_2d(m, n, t, scale, center, dim)<EOL>pos = {v: xy_coords(i, j, u, k) for v, (i, j, u, k) in iteritems(chimera_indices)}<EOL><DEDENT>return pos<EOL>
Positions the nodes of graph G in a Chimera cross topology. NumPy (http://scipy.org) is required for this function. Parameters ---------- G : NetworkX graph Should be a Chimera graph or a subgraph of a Chimera graph. If every node in G has a `chimera_index` attribute, those are used to place the nodes. Otherwise makes a best-effort attempt to find positions. scale : float (default 1.) Scale factor. When scale = 1, all positions fit within [0, 1] on the x-axis and [-1, 0] on the y-axis. center : None or array (default None) Coordinates of the top left corner. dim : int (default 2) Number of dimensions. When dim > 2, all extra dimensions are set to 0. Returns ------- pos : dict A dictionary of positions keyed by node. Examples -------- >>> G = dnx.chimera_graph(1) >>> pos = dnx.chimera_layout(G)
f14407:m0
def chimera_node_placer_2d(m, n, t, scale=<NUM_LIT:1.>, center=None, dim=<NUM_LIT:2>):
import numpy as np<EOL>tile_center = t // <NUM_LIT:2><EOL>tile_length = t + <NUM_LIT:3> <EOL>scale /= max(m, n) * tile_length - <NUM_LIT:3><EOL>grid_offsets = {}<EOL>if center is None:<EOL><INDENT>center = np.zeros(dim)<EOL><DEDENT>else:<EOL><INDENT>center = np.asarray(center)<EOL><DEDENT>paddims = dim - <NUM_LIT:2><EOL>if paddims < <NUM_LIT:0>:<EOL><INDENT>raise ValueError("<STR_LIT>")<EOL><DEDENT>if len(center) != dim:<EOL><INDENT>raise ValueError("<STR_LIT>")<EOL><DEDENT>def _xy_coords(i, j, u, k):<EOL><INDENT>if k < tile_center:<EOL><INDENT>p = k<EOL><DEDENT>else:<EOL><INDENT>p = k + <NUM_LIT:1><EOL><DEDENT>if u:<EOL><INDENT>xy = np.array([tile_center, -<NUM_LIT:1> * p])<EOL><DEDENT>else:<EOL><INDENT>xy = np.array([p, -<NUM_LIT:1> * tile_center])<EOL><DEDENT>if i > <NUM_LIT:0> or j > <NUM_LIT:0>:<EOL><INDENT>if (i, j) in grid_offsets:<EOL><INDENT>xy += grid_offsets[(i, j)]<EOL><DEDENT>else:<EOL><INDENT>off = np.array([j * tile_length, -<NUM_LIT:1> * i * tile_length])<EOL>xy += off<EOL>grid_offsets[(i, j)] = off<EOL><DEDENT><DEDENT>return np.hstack((xy * scale, np.zeros(paddims))) + center<EOL><DEDENT>return _xy_coords<EOL>
Generates a function that converts Chimera indices to x, y coordinates for a plot. Parameters ---------- m : int Number of rows in the Chimera lattice. n : int Number of columns in the Chimera lattice. t : int Size of the shore within each Chimera tile. scale : float (default 1.) Scale factor. When scale = 1, all positions fit within [0, 1] on the x-axis and [-1, 0] on the y-axis. center : None or array (default None) Coordinates of the top left corner. dim : int (default 2) Number of dimensions. When dim > 2, all extra dimensions are set to 0. Returns ------- xy_coords : function A function that maps a Chimera index (i, j, u, k) in an (m, n, t) Chimera lattice to x,y coordinates such as used by a plot.
f14407:m1
def draw_chimera(G, **kwargs):
draw_qubit_graph(G, chimera_layout(G), **kwargs)<EOL>
Draws graph G in a Chimera cross topology. If `linear_biases` and/or `quadratic_biases` are provided, these are visualized on the plot. Parameters ---------- G : NetworkX graph Should be a Chimera graph or a subgraph of a Chimera graph. linear_biases : dict (optional, default {}) A dict of biases associated with each node in G. Should be of form {node: bias, ...}. Each bias should be numeric. quadratic_biases : dict (optional, default {}) A dict of biases associated with each edge in G. Should be of form {edge: bias, ...}. Each bias should be numeric. Self-loop edges (i.e., :math:`i=j`) are treated as linear biases. kwargs : optional keywords See networkx.draw_networkx() for a description of optional keywords, with the exception of the `pos` parameter which is not used by this function. If `linear_biases` or `quadratic_biases` are provided, any provided `node_color` or `edge_color` arguments are ignored. Examples -------- >>> # Plot 2x2 Chimera unit cells >>> import networkx as nx >>> import dwave_networkx as dnx >>> import matplotlib.pyplot as plt >>> G = dnx.chimera_graph(2, 2, 4) >>> dnx.draw_chimera(G) >>> plt.show() # doctest: +SKIP
f14407:m2
def draw_chimera_embedding(G, *args, **kwargs):
draw_embedding(G, chimera_layout(G), *args, **kwargs)<EOL>
Draws an embedding onto the chimera graph G, according to layout. If interaction_edges is not None, then only display the couplers in that list. If embedded_graph is not None, the only display the couplers between chains with intended couplings according to embedded_graph. Parameters ---------- G : NetworkX graph Should be a Chimera graph or a subgraph of a Chimera graph. emb : dict A dict of chains associated with each node in G. Should be of the form {node: chain, ...}. Chains should be iterables of qubit labels (qubits are nodes in G). embedded_graph : NetworkX graph (optional, default None) A graph which contains all keys of emb as nodes. If specified, edges of G will be considered interactions if and only if they exist between two chains of emb if their keys are connected by an edge in embedded_graph interaction_edges : list (optional, default None) A list of edges which will be used as interactions. show_labels: boolean (optional, default False) If show_labels is True, then each chain in emb is labelled with its key. chain_color : dict (optional, default None) A dict of colors associated with each key in emb. Should be of the form {node: rgba_color, ...}. Colors should be length-4 tuples of floats between 0 and 1 inclusive. If chain_color is None, each chain will be assigned a different color. unused_color : tuple (optional, default (0.9,0.9,0.9,1.0)) The color to use for nodes and edges of G which are not involved in chains, and edges which are neither chain edges nor interactions. If unused_color is None, these nodes and edges will not be shown at all. kwargs : optional keywords See networkx.draw_networkx() for a description of optional keywords, with the exception of the `pos` parameter which is not used by this function. If `linear_biases` or `quadratic_biases` are provided, any provided `node_color` or `edge_color` arguments are ignored.
f14407:m3
def draw_chimera_yield(G, **kwargs):
try:<EOL><INDENT>assert(G.graph["<STR_LIT>"] == "<STR_LIT>")<EOL>m = G.graph["<STR_LIT>"]<EOL>n = G.graph["<STR_LIT>"]<EOL>t = G.graph["<STR_LIT>"]<EOL>coordinates = G.graph["<STR_LIT>"] == "<STR_LIT>"<EOL><DEDENT>except:<EOL><INDENT>raise ValueError("<STR_LIT>")<EOL><DEDENT>perfect_graph = chimera_graph(m,n,t, coordinates=coordinates)<EOL>draw_yield(G, chimera_layout(perfect_graph), perfect_graph, **kwargs)<EOL>
Draws the given graph G with highlighted faults, according to layout. Parameters ---------- G : NetworkX graph The graph to be parsed for faults unused_color : tuple or color string (optional, default (0.9,0.9,0.9,1.0)) The color to use for nodes and edges of G which are not faults. If unused_color is None, these nodes and edges will not be shown at all. fault_color : tuple or color string (optional, default (1.0,0.0,0.0,1.0)) A color to represent nodes absent from the graph G. Colors should be length-4 tuples of floats between 0 and 1 inclusive. fault_shape : string, optional (default='x') The shape of the fault nodes. Specification is as matplotlib.scatter marker, one of 'so^>v<dph8'. fault_style : string, optional (default='dashed') Edge fault line style (solid|dashed|dotted,dashdot) kwargs : optional keywords See networkx.draw_networkx() for a description of optional keywords, with the exception of the `pos` parameter which is not used by this function. If `linear_biases` or `quadratic_biases` are provided, any provided `node_color` or `edge_color` arguments are ignored.
f14407:m4
def draw_path(data, path, draw_options=None, simplify=None):
<EOL>if (<EOL>len(path.vertices) == <NUM_LIT:2><EOL>and all(path.vertices[<NUM_LIT:0>] == path.vertices[<NUM_LIT:1>])<EOL>and "<STR_LIT>" in draw_options<EOL>):<EOL><INDENT>return data, "<STR_LIT>", None, False<EOL><DEDENT>nodes = []<EOL>ff = data["<STR_LIT>"]<EOL>prev = None<EOL>for vert, code in path.iter_segments(simplify=simplify):<EOL><INDENT>is_area = False<EOL>if code == mpl.path.Path.MOVETO:<EOL><INDENT>nodes.append(("<STR_LIT>" + ff + "<STR_LIT:U+002C>" + ff + "<STR_LIT:)>").format(*vert))<EOL><DEDENT>elif code == mpl.path.Path.LINETO:<EOL><INDENT>nodes.append(("<STR_LIT>" + ff + "<STR_LIT:U+002C>" + ff + "<STR_LIT:)>").format(*vert))<EOL><DEDENT>elif code == mpl.path.Path.CURVE3:<EOL><INDENT>assert prev is not None<EOL>Q1 = <NUM_LIT:1.0> / <NUM_LIT> * prev + <NUM_LIT> / <NUM_LIT> * vert[<NUM_LIT:0>:<NUM_LIT:2>]<EOL>Q2 = <NUM_LIT> / <NUM_LIT> * vert[<NUM_LIT:0>:<NUM_LIT:2>] + <NUM_LIT:1.0> / <NUM_LIT> * vert[<NUM_LIT:2>:<NUM_LIT:4>]<EOL>Q3 = vert[<NUM_LIT:2>:<NUM_LIT:4>]<EOL>nodes.append(<EOL>(<EOL>"<STR_LIT>"<EOL>+ ff<EOL>+ "<STR_LIT:U+002C>"<EOL>+ ff<EOL>+ "<STR_LIT>"<EOL>+ "<STR_LIT>"<EOL>+ ff<EOL>+ "<STR_LIT:U+002C>"<EOL>+ ff<EOL>+ "<STR_LIT>"<EOL>+ "<STR_LIT>"<EOL>+ ff<EOL>+ "<STR_LIT:U+002C>"<EOL>+ ff<EOL>+ "<STR_LIT:)>"<EOL>).format(Q1[<NUM_LIT:0>], Q1[<NUM_LIT:1>], Q2[<NUM_LIT:0>], Q2[<NUM_LIT:1>], Q3[<NUM_LIT:0>], Q3[<NUM_LIT:1>])<EOL>)<EOL><DEDENT>elif code == mpl.path.Path.CURVE4:<EOL><INDENT>nodes.append(<EOL>(<EOL>"<STR_LIT>"<EOL>+ ff<EOL>+ "<STR_LIT:U+002C>"<EOL>+ ff<EOL>+ "<STR_LIT>"<EOL>+ "<STR_LIT>"<EOL>+ ff<EOL>+ "<STR_LIT:U+002C>"<EOL>+ ff<EOL>+ "<STR_LIT>"<EOL>+ "<STR_LIT>"<EOL>+ ff<EOL>+ "<STR_LIT:U+002C>"<EOL>+ ff<EOL>+ "<STR_LIT:)>"<EOL>).format(*vert)<EOL>)<EOL><DEDENT>else:<EOL><INDENT>assert code == mpl.path.Path.CLOSEPOLY<EOL>nodes.append("<STR_LIT>")<EOL>is_area = True<EOL><DEDENT>prev = vert[<NUM_LIT:0>:<NUM_LIT:2>]<EOL><DEDENT>do = "<STR_LIT>".format("<STR_LIT:U+002CU+0020>".join(draw_options)) if draw_options else "<STR_LIT>"<EOL>path_command = "<STR_LIT>".format(do, "<STR_LIT:\n>".join(nodes))<EOL>return data, path_command, draw_options, is_area<EOL>
Adds code for drawing an ordinary path in PGFPlots (TikZ).
f14410:m0
def draw_pathcollection(data, obj):
content = []<EOL>assert obj.get_offsets() is not None<EOL>labels = ["<STR_LIT:x>" + <NUM_LIT> * "<STR_LIT:U+0020>", "<STR_LIT:y>" + <NUM_LIT> * "<STR_LIT:U+0020>"]<EOL>dd = obj.get_offsets()<EOL>draw_options = ["<STR_LIT>"]<EOL>table_options = []<EOL>if obj.get_array() is not None:<EOL><INDENT>draw_options.append("<STR_LIT>")<EOL>dd = numpy.column_stack([dd, obj.get_array()])<EOL>labels.append("<STR_LIT>" + <NUM_LIT> * "<STR_LIT:U+0020>")<EOL>draw_options.append("<STR_LIT>")<EOL>table_options.extend(["<STR_LIT>", "<STR_LIT>", "<STR_LIT>"])<EOL>ec = None<EOL>fc = None<EOL>ls = None<EOL><DEDENT>else:<EOL><INDENT>try:<EOL><INDENT>ec = obj.get_edgecolors()[<NUM_LIT:0>]<EOL><DEDENT>except (TypeError, IndexError):<EOL><INDENT>ec = None<EOL><DEDENT>try:<EOL><INDENT>fc = obj.get_facecolors()[<NUM_LIT:0>]<EOL><DEDENT>except (TypeError, IndexError):<EOL><INDENT>fc = None<EOL><DEDENT>try:<EOL><INDENT>ls = obj.get_linestyle()[<NUM_LIT:0>]<EOL><DEDENT>except (TypeError, IndexError):<EOL><INDENT>ls = None<EOL><DEDENT><DEDENT>is_contour = len(dd) == <NUM_LIT:1><EOL>if is_contour:<EOL><INDENT>draw_options = ["<STR_LIT>"]<EOL><DEDENT>data, extra_draw_options = get_draw_options(data, obj, ec, fc, ls, None)<EOL>draw_options.extend(extra_draw_options)<EOL>if obj.get_cmap():<EOL><INDENT>mycolormap, is_custom_cmap = _mpl_cmap2pgf_cmap(obj.get_cmap(), data)<EOL>draw_options.append("<STR_LIT>" + ("<STR_LIT:=>" if is_custom_cmap else "<STR_LIT:/>") + mycolormap)<EOL><DEDENT>legend_text = get_legend_text(obj)<EOL>if legend_text is None and has_legend(obj.axes):<EOL><INDENT>draw_options.append("<STR_LIT>")<EOL><DEDENT>for path in obj.get_paths():<EOL><INDENT>if is_contour:<EOL><INDENT>dd = path.vertices<EOL><DEDENT>if len(obj.get_sizes()) == len(dd):<EOL><INDENT>radii = numpy.sqrt(obj.get_sizes() / numpy.pi)<EOL>dd = numpy.column_stack([dd, radii])<EOL>labels.append("<STR_LIT>" + <NUM_LIT> * "<STR_LIT:U+0020>")<EOL>draw_options.extend(<EOL>[<EOL>"<STR_LIT>"<EOL>"<STR_LIT>",<EOL>"<STR_LIT>"<EOL>"<STR_LIT>",<EOL>]<EOL>)<EOL><DEDENT>do = "<STR_LIT>".format("<STR_LIT:U+002CU+0020>".join(draw_options)) if draw_options else "<STR_LIT>"<EOL>content.append("<STR_LIT>".format(do))<EOL>to = "<STR_LIT>".format("<STR_LIT:U+002CU+0020>".join(table_options)) if table_options else "<STR_LIT>"<EOL>content.append("<STR_LIT>".format(to))<EOL>content.append(("<STR_LIT:U+0020>".join(labels)).strip() + "<STR_LIT:\n>")<EOL>ff = data["<STR_LIT>"]<EOL>fmt = ("<STR_LIT:U+0020>".join(dd.shape[<NUM_LIT:1>] * [ff])) + "<STR_LIT:\n>"<EOL>for d in dd:<EOL><INDENT>content.append(fmt.format(*tuple(d)))<EOL><DEDENT>content.append("<STR_LIT>")<EOL><DEDENT>if legend_text is not None:<EOL><INDENT>content.append("<STR_LIT>".format(legend_text))<EOL><DEDENT>return data, content<EOL>
Returns PGFPlots code for a number of patch objects.
f14410:m1
def get_draw_options(data, obj, ec, fc, style, width):
draw_options = []<EOL>if ec is not None:<EOL><INDENT>data, col, ec_rgba = color.mpl_color2xcolor(data, ec)<EOL>if ec_rgba[<NUM_LIT:3>] != <NUM_LIT:0.0>:<EOL><INDENT>draw_options.append("<STR_LIT>".format(col))<EOL><DEDENT><DEDENT>if fc is not None:<EOL><INDENT>data, col, fc_rgba = color.mpl_color2xcolor(data, fc)<EOL>if fc_rgba[<NUM_LIT:3>] != <NUM_LIT:0.0>:<EOL><INDENT>draw_options.append("<STR_LIT>".format(col))<EOL><DEDENT><DEDENT>ff = data["<STR_LIT>"]<EOL>if (<EOL>ec is not None<EOL>and fc is not None<EOL>and ec_rgba[<NUM_LIT:3>] != <NUM_LIT:1.0><EOL>and ec_rgba[<NUM_LIT:3>] == fc_rgba[<NUM_LIT:3>]<EOL>):<EOL><INDENT>draw_options.append(("<STR_LIT>" + ff).format(ec[<NUM_LIT:3>]))<EOL><DEDENT>else:<EOL><INDENT>if ec is not None and ec_rgba[<NUM_LIT:3>] != <NUM_LIT:1.0>:<EOL><INDENT>draw_options.append(("<STR_LIT>" + ff).format(ec_rgba[<NUM_LIT:3>]))<EOL><DEDENT>if fc is not None and fc_rgba[<NUM_LIT:3>] != <NUM_LIT:1.0>:<EOL><INDENT>draw_options.append(("<STR_LIT>" + ff).format(fc_rgba[<NUM_LIT:3>]))<EOL><DEDENT><DEDENT>if width is not None:<EOL><INDENT>w = mpl_linewidth2pgfp_linewidth(data, width)<EOL>if w:<EOL><INDENT>draw_options.append(w)<EOL><DEDENT><DEDENT>if style is not None:<EOL><INDENT>ls = mpl_linestyle2pgfplots_linestyle(style)<EOL>if ls is not None and ls != "<STR_LIT>":<EOL><INDENT>draw_options.append(ls)<EOL><DEDENT><DEDENT>return data, draw_options<EOL>
Get the draw options for a given (patch) object.
f14410:m2
def mpl_linestyle2pgfplots_linestyle(line_style, line=None):
<EOL>if isinstance(line_style, tuple):<EOL><INDENT>if line_style[<NUM_LIT:0>] is None:<EOL><INDENT>return None<EOL><DEDENT>if len(line_style[<NUM_LIT:1>]) == <NUM_LIT:2>:<EOL><INDENT>return "<STR_LIT>".format(*line_style[<NUM_LIT:1>])<EOL><DEDENT>assert len(line_style[<NUM_LIT:1>]) == <NUM_LIT:4><EOL>return "<STR_LIT>".format(*line_style[<NUM_LIT:1>])<EOL><DEDENT>if isinstance(line, mpl.lines.Line2D) and line.is_dashed():<EOL><INDENT>default_dashOffset, default_dashSeq = mpl.lines._get_dash_pattern(line_style)<EOL>dashSeq = line._us_dashSeq<EOL>dashOffset = line._us_dashOffset<EOL>lst = list()<EOL>if dashSeq != default_dashSeq:<EOL><INDENT>format_string = "<STR_LIT:U+0020>".join(len(dashSeq) // <NUM_LIT:2> * ["<STR_LIT>"])<EOL>lst.append("<STR_LIT>" + format_string.format(*dashSeq))<EOL><DEDENT>if dashOffset != default_dashOffset:<EOL><INDENT>lst.append("<STR_LIT>".format(dashOffset))<EOL><DEDENT>if len(lst) > <NUM_LIT:0>:<EOL><INDENT>return "<STR_LIT:U+002CU+0020>".join(lst)<EOL><DEDENT><DEDENT>return {<EOL>"<STR_LIT>": None,<EOL>"<STR_LIT:None>": None,<EOL>"<STR_LIT:none>": None, <EOL>"<STR_LIT:->": "<STR_LIT>",<EOL>"<STR_LIT>": "<STR_LIT>",<EOL>"<STR_LIT::>": "<STR_LIT>",<EOL>"<STR_LIT>": "<STR_LIT>",<EOL>"<STR_LIT>": "<STR_LIT>",<EOL>}[line_style]<EOL>
Translates a line style of matplotlib to the corresponding style in PGFPlots.
f14410:m4
def get_legend_text(obj):
leg = obj.axes.get_legend()<EOL>if leg is None:<EOL><INDENT>return None<EOL><DEDENT>keys = [l.get_label() for l in leg.legendHandles if l is not None]<EOL>values = [l.get_text() for l in leg.texts]<EOL>label = obj.get_label()<EOL>d = dict(zip(keys, values))<EOL>if label in d:<EOL><INDENT>return d[label]<EOL><DEDENT>return None<EOL>
Check if line is in legend.
f14411:m1
def transform_to_data_coordinates(obj, xdata, ydata):
if obj.axes is not None and obj.get_transform() != obj.axes.transData:<EOL><INDENT>points = numpy.array([xdata, ydata]).T<EOL>transform = matplotlib.transforms.composite_transform_factory(<EOL>obj.get_transform(), obj.axes.transData.inverted()<EOL>)<EOL>return transform.transform(points).T<EOL><DEDENT>return xdata, ydata<EOL>
The coordinates might not be in data coordinates, but could be sometimes in axes coordinates. For example, the matplotlib command axes.axvline(2) will have the y coordinates set to 0 and 1, not to the limits. Therefore, a two-stage transform has to be applied: 1. first transforming to display coordinates, then 2. from display to data.
f14411:m2
def draw_legend(data, obj):
texts = []<EOL>children_alignment = []<EOL>for text in obj.texts:<EOL><INDENT>texts.append("<STR_LIT:{}>".format(text.get_text()))<EOL>children_alignment.append("<STR_LIT:{}>".format(text.get_horizontalalignment()))<EOL><DEDENT>loc = obj._loc if obj._loc != <NUM_LIT:0> else _get_location_from_best(obj)<EOL>pad = <NUM_LIT><EOL>position, anchor = {<EOL><NUM_LIT:1>: (None, None), <EOL><NUM_LIT:2>: ([pad, <NUM_LIT:1.0> - pad], "<STR_LIT>"), <EOL><NUM_LIT:3>: ([pad, pad], "<STR_LIT>"), <EOL><NUM_LIT:4>: ([<NUM_LIT:1.0> - pad, pad], "<STR_LIT>"), <EOL><NUM_LIT:5>: ([<NUM_LIT:1.0> - pad, <NUM_LIT:0.5>], "<STR_LIT>"), <EOL><NUM_LIT:6>: ([<NUM_LIT:3> * pad, <NUM_LIT:0.5>], "<STR_LIT>"), <EOL><NUM_LIT:7>: ([<NUM_LIT:1.0> - <NUM_LIT:3> * pad, <NUM_LIT:0.5>], "<STR_LIT>"), <EOL><NUM_LIT:8>: ([<NUM_LIT:0.5>, <NUM_LIT:3> * pad], "<STR_LIT>"), <EOL><NUM_LIT:9>: ([<NUM_LIT:0.5>, <NUM_LIT:1.0> - <NUM_LIT:3> * pad], "<STR_LIT>"), <EOL><NUM_LIT:10>: ([<NUM_LIT:0.5>, <NUM_LIT:0.5>], "<STR_LIT>"), <EOL>}[loc]<EOL>if obj._bbox_to_anchor:<EOL><INDENT>bbox_center = obj.get_bbox_to_anchor()._bbox._points[<NUM_LIT:1>]<EOL>position = [bbox_center[<NUM_LIT:0>], bbox_center[<NUM_LIT:1>]]<EOL><DEDENT>legend_style = []<EOL>if position:<EOL><INDENT>ff = data["<STR_LIT>"]<EOL>legend_style.append(<EOL>("<STR_LIT>" + ff + "<STR_LIT:U+002C>" + ff + "<STR_LIT>").format(position[<NUM_LIT:0>], position[<NUM_LIT:1>])<EOL>)<EOL><DEDENT>if anchor:<EOL><INDENT>legend_style.append("<STR_LIT>".format(anchor))<EOL><DEDENT>if obj.get_frame_on():<EOL><INDENT>edgecolor = obj.get_frame().get_edgecolor()<EOL>data, frame_xcolor, _ = mycol.mpl_color2xcolor(data, edgecolor)<EOL>if frame_xcolor != "<STR_LIT>": <EOL><INDENT>legend_style.append("<STR_LIT>".format(frame_xcolor))<EOL><DEDENT><DEDENT>else:<EOL><INDENT>legend_style.append("<STR_LIT>")<EOL><DEDENT>facecolor = obj.get_frame().get_facecolor()<EOL>data, fill_xcolor, _ = mycol.mpl_color2xcolor(data, facecolor)<EOL>if fill_xcolor != "<STR_LIT>": <EOL><INDENT>legend_style.append("<STR_LIT>".format(fill_xcolor))<EOL><DEDENT>try:<EOL><INDENT>alignment = children_alignment[<NUM_LIT:0>]<EOL><DEDENT>except IndexError:<EOL><INDENT>alignment = None<EOL><DEDENT>for child_alignment in children_alignment:<EOL><INDENT>if alignment != child_alignment:<EOL><INDENT>warnings.warn("<STR_LIT>")<EOL>alignment = None<EOL>break<EOL><DEDENT><DEDENT>if alignment:<EOL><INDENT>data["<STR_LIT>"].axis_options.append(<EOL>"<STR_LIT>".format(alignment)<EOL>)<EOL><DEDENT>if obj._ncol != <NUM_LIT:1>:<EOL><INDENT>data["<STR_LIT>"].axis_options.append("<STR_LIT>".format(obj._ncol))<EOL><DEDENT>if legend_style:<EOL><INDENT>style = "<STR_LIT>".format("<STR_LIT:U+002CU+0020>".join(legend_style))<EOL>data["<STR_LIT>"].axis_options.append(style)<EOL><DEDENT>return data<EOL>
Adds legend code.
f14412:m0
def draw_image(data, obj):
content = []<EOL>filename, rel_filepath = files.new_filename(data, "<STR_LIT>", "<STR_LIT>")<EOL>img_array = obj.get_array()<EOL>dims = img_array.shape<EOL>if len(dims) == <NUM_LIT:2>: <EOL><INDENT>clims = obj.get_clim()<EOL>mpl.pyplot.imsave(<EOL>fname=filename,<EOL>arr=img_array,<EOL>cmap=obj.get_cmap(),<EOL>vmin=clims[<NUM_LIT:0>],<EOL>vmax=clims[<NUM_LIT:1>],<EOL>origin=obj.origin,<EOL>)<EOL><DEDENT>else:<EOL><INDENT>assert len(dims) == <NUM_LIT:3> and dims[<NUM_LIT:2>] in [<NUM_LIT:3>, <NUM_LIT:4>]<EOL>if obj.origin == "<STR_LIT>":<EOL><INDENT>img_array = numpy.flipud(img_array)<EOL><DEDENT>image = PIL.Image.fromarray(numpy.uint8(img_array * <NUM_LIT:255>))<EOL>image.save(filename, origin=obj.origin)<EOL><DEDENT>extent = obj.get_extent()<EOL>if not isinstance(extent, tuple):<EOL><INDENT>extent = tuple(extent)<EOL><DEDENT>ff = data["<STR_LIT>"]<EOL>content.append(<EOL>(<EOL>"<STR_LIT>"<EOL>"<STR_LIT>" + ff + "<STR_LIT>" + ff + "<STR_LIT:U+002CU+0020>"<EOL>"<STR_LIT>" + ff + "<STR_LIT>" + ff + "<STR_LIT>"<EOL>).format(*(extent + (rel_filepath,)))<EOL>)<EOL>return data, content<EOL>
Returns the PGFPlots code for an image environment.
f14413:m0
def new_filename(data, file_kind, ext):
nb_key = file_kind + "<STR_LIT>"<EOL>if nb_key not in data.keys():<EOL><INDENT>data[nb_key] = -<NUM_LIT:1><EOL><DEDENT>if not data["<STR_LIT>"]:<EOL><INDENT>file_exists = True<EOL>while file_exists:<EOL><INDENT>data[nb_key] = data[nb_key] + <NUM_LIT:1><EOL>filename, name = _gen_filename(data, nb_key, ext)<EOL>file_exists = os.path.isfile(filename)<EOL><DEDENT><DEDENT>else:<EOL><INDENT>data[nb_key] = data[nb_key] + <NUM_LIT:1><EOL>filename, name = _gen_filename(data, nb_key, ext)<EOL><DEDENT>if data["<STR_LIT>"]:<EOL><INDENT>rel_filepath = posixpath.join(data["<STR_LIT>"], name)<EOL><DEDENT>else:<EOL><INDENT>rel_filepath = name<EOL><DEDENT>return filename, rel_filepath<EOL>
Returns an available filename. :param file_kind: Name under which numbering is recorded, such as 'img' or 'table'. :type file_kind: str :param ext: Filename extension. :type ext: str :returns: (filename, rel_filepath) where filename is a path in the filesystem and rel_filepath is the path to be used in the tex code.
f14414:m1
def draw_quadmesh(data, obj):
content = []<EOL>filename, rel_filepath = files.new_filename(data, "<STR_LIT>", "<STR_LIT>")<EOL>dpi = data["<STR_LIT>"]<EOL>fig_dpi = obj.figure.get_dpi()<EOL>obj.figure.set_dpi(dpi)<EOL>from matplotlib.backends.backend_agg import RendererAgg<EOL>cbox = obj.get_clip_box()<EOL>width = int(round(cbox.extents[<NUM_LIT:2>]))<EOL>height = int(round(cbox.extents[<NUM_LIT:3>]))<EOL>ren = RendererAgg(width, height, dpi)<EOL>obj.draw(ren)<EOL>image = Image.frombuffer(<EOL>"<STR_LIT>", ren.get_canvas_width_height(), ren.buffer_rgba(), "<STR_LIT>", "<STR_LIT>", <NUM_LIT:0>, <NUM_LIT:1><EOL>)<EOL>box = (<EOL>int(round(cbox.extents[<NUM_LIT:0>])),<EOL><NUM_LIT:0>,<EOL>int(round(cbox.extents[<NUM_LIT:2>])),<EOL>int(round(cbox.extents[<NUM_LIT:3>] - cbox.extents[<NUM_LIT:1>])),<EOL>)<EOL>cropped = image.crop(box)<EOL>cropped.save(filename)<EOL>obj.figure.set_dpi(fig_dpi)<EOL>extent = obj.axes.get_xlim() + obj.axes.get_ylim()<EOL>ff = data["<STR_LIT>"]<EOL>content.append(<EOL>(<EOL>"<STR_LIT>"<EOL>"<STR_LIT>" + ff + "<STR_LIT>" + ff + "<STR_LIT:U+002CU+0020>"<EOL>"<STR_LIT>" + ff + "<STR_LIT>" + ff + "<STR_LIT>"<EOL>).format(*(extent + (rel_filepath,)))<EOL>)<EOL>return data, content<EOL>
Returns the PGFPlots code for an graphics environment holding a rendering of the object.
f14415:m0
def draw_line2d(data, obj):
content = []<EOL>addplot_options = []<EOL>if len(obj.get_xdata()) == <NUM_LIT:0>:<EOL><INDENT>return data, []<EOL><DEDENT>line_width = mypath.mpl_linewidth2pgfp_linewidth(data, obj.get_linewidth())<EOL>if line_width:<EOL><INDENT>addplot_options.append(line_width)<EOL><DEDENT>color = obj.get_color()<EOL>data, line_xcolor, _ = mycol.mpl_color2xcolor(data, color)<EOL>addplot_options.append(line_xcolor)<EOL>alpha = obj.get_alpha()<EOL>if alpha is not None:<EOL><INDENT>addplot_options.append("<STR_LIT>".format(alpha))<EOL><DEDENT>linestyle = mypath.mpl_linestyle2pgfplots_linestyle(obj.get_linestyle(), line=obj)<EOL>if linestyle is not None and linestyle != "<STR_LIT>":<EOL><INDENT>addplot_options.append(linestyle)<EOL><DEDENT>marker_face_color = obj.get_markerfacecolor()<EOL>marker_edge_color = obj.get_markeredgecolor()<EOL>data, marker, extra_mark_options = _mpl_marker2pgfp_marker(<EOL>data, obj.get_marker(), marker_face_color<EOL>)<EOL>if marker:<EOL><INDENT>_marker(<EOL>obj,<EOL>data,<EOL>marker,<EOL>addplot_options,<EOL>extra_mark_options,<EOL>marker_face_color,<EOL>marker_edge_color,<EOL>line_xcolor,<EOL>)<EOL><DEDENT>if marker and linestyle is None:<EOL><INDENT>addplot_options.append("<STR_LIT>")<EOL><DEDENT>legend_text = get_legend_text(obj)<EOL>if legend_text is None and has_legend(obj.axes):<EOL><INDENT>addplot_options.append("<STR_LIT>")<EOL><DEDENT>content.append("<STR_LIT>")<EOL>if addplot_options:<EOL><INDENT>content.append("<STR_LIT>".format("<STR_LIT:U+002CU+0020>".join(addplot_options)))<EOL><DEDENT>c, axis_options = _table(obj, data)<EOL>content += c<EOL>if legend_text is not None:<EOL><INDENT>content.append("<STR_LIT>".format(legend_text))<EOL><DEDENT>return data, content<EOL>
Returns the PGFPlots code for an Line2D environment.
f14416:m0
def draw_linecollection(data, obj):
content = []<EOL>edgecolors = obj.get_edgecolors()<EOL>linestyles = obj.get_linestyles()<EOL>linewidths = obj.get_linewidths()<EOL>paths = obj.get_paths()<EOL>for i, path in enumerate(paths):<EOL><INDENT>color = edgecolors[i] if i < len(edgecolors) else edgecolors[<NUM_LIT:0>]<EOL>style = linestyles[i] if i < len(linestyles) else linestyles[<NUM_LIT:0>]<EOL>width = linewidths[i] if i < len(linewidths) else linewidths[<NUM_LIT:0>]<EOL>data, options = mypath.get_draw_options(data, obj, color, None, style, width)<EOL>data, cont, _, _ = mypath.draw_path(<EOL>data, path, draw_options=options, simplify=False<EOL>)<EOL>content.append(cont + "<STR_LIT:\n>")<EOL><DEDENT>return data, content<EOL>
Returns Pgfplots code for a number of patch objects.
f14416:m1
def _mpl_marker2pgfp_marker(data, mpl_marker, marker_face_color):
<EOL>try:<EOL><INDENT>pgfplots_marker = _MP_MARKER2PGF_MARKER[mpl_marker]<EOL><DEDENT>except KeyError:<EOL><INDENT>pass<EOL><DEDENT>else:<EOL><INDENT>if (marker_face_color is not None) and pgfplots_marker == "<STR_LIT:o>":<EOL><INDENT>pgfplots_marker = "<STR_LIT:*>"<EOL>data["<STR_LIT>"].add("<STR_LIT>")<EOL><DEDENT>marker_options = None<EOL>return (data, pgfplots_marker, marker_options)<EOL><DEDENT>try:<EOL><INDENT>data["<STR_LIT>"].add("<STR_LIT>")<EOL>pgfplots_marker, marker_options = _MP_MARKER2PLOTMARKS[mpl_marker]<EOL><DEDENT>except KeyError:<EOL><INDENT>pass<EOL><DEDENT>else:<EOL><INDENT>if (<EOL>marker_face_color is not None<EOL>and (<EOL>not isinstance(marker_face_color, str)<EOL>or marker_face_color.lower() != "<STR_LIT:none>"<EOL>)<EOL>and pgfplots_marker not in ["<STR_LIT:|>", "<STR_LIT:->", "<STR_LIT>", "<STR_LIT>"]<EOL>):<EOL><INDENT>pgfplots_marker += "<STR_LIT:*>"<EOL><DEDENT>return (data, pgfplots_marker, marker_options)<EOL><DEDENT>return data, None, None<EOL>
Translates a marker style of matplotlib to the corresponding style in PGFPlots.
f14416:m2
def get_tikz_code(<EOL>figure="<STR_LIT>",<EOL>filepath=None,<EOL>figurewidth=None,<EOL>figureheight=None,<EOL>textsize=<NUM_LIT>,<EOL>tex_relative_path_to_data=None,<EOL>externalize_tables=False,<EOL>override_externals=False,<EOL>strict=False,<EOL>wrap=True,<EOL>add_axis_environment=True,<EOL>extra_axis_parameters=None,<EOL>extra_tikzpicture_parameters=None,<EOL>dpi=None,<EOL>show_info=False,<EOL>include_disclaimer=True,<EOL>standalone=False,<EOL>float_format="<STR_LIT>",<EOL>table_row_sep="<STR_LIT:\n>",<EOL>):
<EOL>if figure == "<STR_LIT>":<EOL><INDENT>figure = plt.gcf()<EOL><DEDENT>data = {}<EOL>data["<STR_LIT>"] = figurewidth<EOL>data["<STR_LIT>"] = figureheight<EOL>data["<STR_LIT>"] = tex_relative_path_to_data<EOL>data["<STR_LIT>"] = externalize_tables<EOL>data["<STR_LIT>"] = override_externals<EOL>if filepath:<EOL><INDENT>data["<STR_LIT>"] = os.path.dirname(filepath)<EOL><DEDENT>else:<EOL><INDENT>directory = tempfile.mkdtemp()<EOL>data["<STR_LIT>"] = directory<EOL><DEDENT>data["<STR_LIT>"] = (<EOL>os.path.splitext(os.path.basename(filepath))[<NUM_LIT:0>] if filepath else "<STR_LIT>"<EOL>)<EOL>data["<STR_LIT:strict>"] = strict<EOL>data["<STR_LIT>"] = set()<EOL>data["<STR_LIT>"] = set()<EOL>data["<STR_LIT>"] = textsize<EOL>data["<STR_LIT>"] = {}<EOL>data["<STR_LIT>"] = []<EOL>data["<STR_LIT>"] = extra_tikzpicture_parameters<EOL>data["<STR_LIT>"] = add_axis_environment<EOL>data["<STR_LIT>"] = show_info<EOL>data["<STR_LIT>"] = set()<EOL>if extra_axis_parameters:<EOL><INDENT>data["<STR_LIT>"] = set(extra_axis_parameters).copy()<EOL><DEDENT>else:<EOL><INDENT>data["<STR_LIT>"] = set()<EOL><DEDENT>if dpi:<EOL><INDENT>data["<STR_LIT>"] = dpi<EOL><DEDENT>else:<EOL><INDENT>savefig_dpi = mpl.rcParams["<STR_LIT>"]<EOL>data["<STR_LIT>"] = (<EOL>savefig_dpi if isinstance(savefig_dpi, int) else mpl.rcParams["<STR_LIT>"]<EOL>)<EOL><DEDENT>data["<STR_LIT>"] = float_format<EOL>data["<STR_LIT>"] = table_row_sep<EOL>if show_info:<EOL><INDENT>_print_pgfplot_libs_message(data)<EOL><DEDENT>data, content = _recurse(data, figure)<EOL>if "<STR_LIT>" in data and data["<STR_LIT>"]:<EOL><INDENT>content.extend("<STR_LIT>")<EOL><DEDENT>code = """<STR_LIT>"""<EOL>if include_disclaimer:<EOL><INDENT>disclaimer = "<STR_LIT>".format(__version__)<EOL>code += _tex_comment(disclaimer)<EOL><DEDENT>if wrap and add_axis_environment:<EOL><INDENT>code += "<STR_LIT>"<EOL>if extra_tikzpicture_parameters:<EOL><INDENT>code += "<STR_LIT>".join(data["<STR_LIT>"])<EOL>code += "<STR_LIT:\n>"<EOL><DEDENT><DEDENT>coldefs = _get_color_definitions(data)<EOL>if coldefs:<EOL><INDENT>code += "<STR_LIT:\n>".join(coldefs)<EOL>code += "<STR_LIT>"<EOL><DEDENT>code += "<STR_LIT>".join(content)<EOL>if wrap and add_axis_environment:<EOL><INDENT>code += "<STR_LIT>"<EOL><DEDENT>if standalone:<EOL><INDENT>code = """<STR_LIT>""".format(<EOL>code<EOL>)<EOL><DEDENT>return code<EOL>
Main function. Here, the recursion into the image starts and the contents are picked up. The actual file gets written in this routine. :param figure: either a Figure object or 'gcf' (default). :param figurewidth: If not ``None``, this will be used as figure width within the TikZ/PGFPlots output. If ``figureheight`` is not given, ``matplotlib2tikz`` will try to preserve the original width/height ratio. Note that ``figurewidth`` can be a string literal, such as ``'\\figurewidth'``. :type figurewidth: str :param figureheight: If not ``None``, this will be used as figure height within the TikZ/PGFPlots output. If ``figurewidth`` is not given, ``matplotlib2tikz`` will try to preserve the original width/height ratio. Note that ``figurewidth`` can be a string literal, such as ``'\\figureheight'``. :type figureheight: str :param textsize: The text size (in pt) that the target latex document is using. Default is 10.0. :type textsize: float :param tex_relative_path_to_data: In some cases, the TikZ file will have to refer to another file, e.g., a PNG for image plots. When ``\\input`` into a regular LaTeX document, the additional file is looked for in a folder relative to the LaTeX file, not the TikZ file. This arguments optionally sets the relative path from the LaTeX file to the data. :type tex_relative_path_to_data: str :param externalize_tables: Whether or not to externalize plot data tables into tsv files. :type externalize_tables: bool :param override_externals: Whether or not to override existing external files (such as tsv or images) with conflicting names (the alternative is to choose other names). :type override_externals: bool :param strict: Whether or not to strictly stick to matplotlib's appearance. This influences, for example, whether tick marks are set exactly as in the matplotlib plot, or if TikZ/PGFPlots can decide where to put the ticks. :type strict: bool :param wrap: Whether ``'\\begin{tikzpicture}'`` and ``'\\end{tikzpicture}'`` will be written. One might need to provide custom arguments to the environment (eg. scale= etc.). Default is ``True``. :type wrap: bool :param add_axis_environment: Whether ``'\\begin{axis}[...]'`` and ``'\\end{axis}'`` will be written. One needs to set the environment in the document. If ``False`` additionally sets ``wrap=False``. Default is ``True``. :type add_axis_environment: bool :param extra_axis_parameters: Extra axis options to be passed (as a list or set) to pgfplots. Default is ``None``. :type extra_axis_parameters: a list or set of strings for the pfgplots axes. :param extra_tikzpicture_parameters: Extra tikzpicture options to be passed (as a set) to pgfplots. :type extra_tikzpicture_parameters: a set of strings for the pfgplots tikzpicture. :param dpi: The resolution in dots per inch of the rendered image in case of QuadMesh plots. If ``None`` it will default to the value ``savefig.dpi`` from matplotlib.rcParams. Default is ``None``. :type dpi: int :param show_info: Show extra info on the command line. Default is ``False``. :type show_info: bool :param include_disclaimer: Include matplotlib2tikz disclaimer in the output. Set ``False`` to make tests reproducible. Default is ``True``. :type include_disclaimer: bool :param standalone: Include wrapper code for a standalone LaTeX file. :type standalone: bool :param float_format: Format for float entities. Default is ```"{:.15g}"```. :type float_format: str :param table_row_sep: Row separator for table data. Default is ```"\\n"```. :type table_row_sep: str :returns: None The following optional attributes of matplotlib's objects are recognized and handled: - axes.Axes._matplotlib2tikz_anchors This attribute can be set to a list of ((x,y), anchor_name) tuples. Invisible nodes at the respective location will be created which can be referenced from outside the axis environment.
f14417:m0
def save(filepath, *args, encoding=None, **kwargs):
code = get_tikz_code(*args, filepath=filepath, **kwargs)<EOL>file_handle = codecs.open(filepath, "<STR_LIT:w>", encoding)<EOL>try:<EOL><INDENT>file_handle.write(code)<EOL><DEDENT>except UnicodeEncodeError:<EOL><INDENT>file_handle.write(six.text_type(code).encode("<STR_LIT:utf-8>"))<EOL><DEDENT>file_handle.close()<EOL>return<EOL>
Same as `get_tikz_code()`, but actually saves the code to a file. :param filepath: The file to which the TikZ output will be written. :type filepath: str :param encoding: Sets the text encoding of the output file, e.g. 'utf-8'. For supported values: see ``codecs`` module. :returns: None
f14417:m1
def _tex_comment(comment):
return "<STR_LIT>" + str.replace(comment, "<STR_LIT:\n>", "<STR_LIT>") + "<STR_LIT:\n>"<EOL>
Prepends each line in string with the LaTeX comment key, '%'.
f14417:m2
def _get_color_definitions(data):
definitions = []<EOL>fmt = "<STR_LIT>" + "<STR_LIT:U+002C>".join(<NUM_LIT:3> * [data["<STR_LIT>"]]) + "<STR_LIT>"<EOL>for name, rgb in data["<STR_LIT>"].items():<EOL><INDENT>definitions.append(fmt.format(name, rgb[<NUM_LIT:0>], rgb[<NUM_LIT:1>], rgb[<NUM_LIT:2>]))<EOL><DEDENT>return definitions<EOL>
Returns the list of custom color definitions for the TikZ file.
f14417:m3
def _print_pgfplot_libs_message(data):
pgfplotslibs = "<STR_LIT:U+002C>".join(list(data["<STR_LIT>"]))<EOL>tikzlibs = "<STR_LIT:U+002C>".join(list(data["<STR_LIT>"]))<EOL>print(<NUM_LIT> * "<STR_LIT:=>")<EOL>print("<STR_LIT>")<EOL>print("<STR_LIT>")<EOL>print("<STR_LIT>")<EOL>print("<STR_LIT>")<EOL>if tikzlibs:<EOL><INDENT>print("<STR_LIT>" + tikzlibs + "<STR_LIT:}>")<EOL><DEDENT>if pgfplotslibs:<EOL><INDENT>print("<STR_LIT>" + pgfplotslibs + "<STR_LIT:}>")<EOL><DEDENT>print(<NUM_LIT> * "<STR_LIT:=>")<EOL>return<EOL>
Prints message to screen indicating the use of PGFPlots and its libraries.
f14417:m4
def _recurse(data, obj):
content = _ContentManager()<EOL>for child in obj.get_children():<EOL><INDENT>if isinstance(child, mpl.spines.Spine):<EOL><INDENT>continue<EOL><DEDENT>if isinstance(child, mpl.axes.Axes):<EOL><INDENT>ax = axes.Axes(data, child)<EOL>if ax.is_colorbar:<EOL><INDENT>continue<EOL><DEDENT>if data["<STR_LIT>"]:<EOL><INDENT>ax.axis_options.extend(data["<STR_LIT>"])<EOL><DEDENT>data["<STR_LIT>"] = child<EOL>data["<STR_LIT>"] = ax<EOL>data, children_content = _recurse(data, child)<EOL>if data["<STR_LIT>"]:<EOL><INDENT>content.extend(<EOL>ax.get_begin_code() + children_content + [ax.get_end_code(data)], <NUM_LIT:0><EOL>)<EOL><DEDENT>else:<EOL><INDENT>content.extend(children_content, <NUM_LIT:0>)<EOL>if data["<STR_LIT>"]:<EOL><INDENT>print("<STR_LIT>")<EOL>print("<STR_LIT>")<EOL>print("<STR_LIT>".join(ax.get_begin_code()[<NUM_LIT:1>:]))<EOL>print("<STR_LIT>")<EOL><DEDENT><DEDENT><DEDENT>elif isinstance(child, mpl.lines.Line2D):<EOL><INDENT>data, cont = line2d.draw_line2d(data, child)<EOL>content.extend(cont, child.get_zorder())<EOL><DEDENT>elif isinstance(child, mpl.image.AxesImage):<EOL><INDENT>data, cont = img.draw_image(data, child)<EOL>content.extend(cont, child.get_zorder())<EOL><DEDENT>elif isinstance(child, mpl.patches.Patch):<EOL><INDENT>data, cont = patch.draw_patch(data, child)<EOL>content.extend(cont, child.get_zorder())<EOL><DEDENT>elif isinstance(<EOL>child, (mpl.collections.PatchCollection, mpl.collections.PolyCollection)<EOL>):<EOL><INDENT>data, cont = patch.draw_patchcollection(data, child)<EOL>content.extend(cont, child.get_zorder())<EOL><DEDENT>elif isinstance(child, mpl.collections.PathCollection):<EOL><INDENT>data, cont = path.draw_pathcollection(data, child)<EOL>content.extend(cont, child.get_zorder())<EOL><DEDENT>elif isinstance(child, mpl.collections.LineCollection):<EOL><INDENT>data, cont = line2d.draw_linecollection(data, child)<EOL>content.extend(cont, child.get_zorder())<EOL><DEDENT>elif isinstance(child, mpl.collections.QuadMesh):<EOL><INDENT>data, cont = qmsh.draw_quadmesh(data, child)<EOL>content.extend(cont, child.get_zorder())<EOL><DEDENT>elif isinstance(child, mpl.legend.Legend):<EOL><INDENT>data = legend.draw_legend(data, child)<EOL>if data["<STR_LIT>"]:<EOL><INDENT>content.extend(data["<STR_LIT>"], <NUM_LIT:0>)<EOL><DEDENT><DEDENT>elif isinstance(child, (mpl.text.Text, mpl.text.Annotation)):<EOL><INDENT>data, cont = text.draw_text(data, child)<EOL>content.extend(cont, child.get_zorder())<EOL><DEDENT>elif isinstance(child, (mpl.axis.XAxis, mpl.axis.YAxis)):<EOL><INDENT>pass<EOL><DEDENT>else:<EOL><INDENT>warnings.warn(<EOL>"<STR_LIT>".format(<EOL>type(child)<EOL>)<EOL>)<EOL><DEDENT><DEDENT>return data, content.flatten()<EOL>
Iterates over all children of the current object, gathers the contents contributing to the resulting PGFPlots file, and returns those.
f14417:m5
def extend(self, content, zorder):
if zorder not in self._content:<EOL><INDENT>self._content[zorder] = []<EOL><DEDENT>self._content[zorder].extend(content)<EOL>
Extends with a list and a z-order
f14417:c0:m1
def draw_text(data, obj):
content = []<EOL>properties = []<EOL>style = []<EOL>if isinstance(obj, mpl.text.Annotation):<EOL><INDENT>_annotation(obj, data, content)<EOL><DEDENT>pos = obj.get_position()<EOL>text = obj.get_text()<EOL>if text in ["<STR_LIT>", data["<STR_LIT>"]]:<EOL><INDENT>return data, content<EOL><DEDENT>size = obj.get_size()<EOL>bbox = obj.get_bbox_patch()<EOL>converter = mpl.colors.ColorConverter()<EOL>scaling = <NUM_LIT:0.5> * size / data["<STR_LIT>"]<EOL>ff = data["<STR_LIT>"]<EOL>if scaling != <NUM_LIT:1.0>:<EOL><INDENT>properties.append(("<STR_LIT>" + ff).format(scaling))<EOL><DEDENT>if bbox is not None:<EOL><INDENT>_bbox(bbox, data, properties, scaling)<EOL><DEDENT>ha = obj.get_ha()<EOL>va = obj.get_va()<EOL>anchor = _transform_positioning(ha, va)<EOL>if anchor is not None:<EOL><INDENT>properties.append(anchor)<EOL><DEDENT>data, col, _ = color.mpl_color2xcolor(data, converter.to_rgb(obj.get_color()))<EOL>properties.append("<STR_LIT>".format(col))<EOL>properties.append("<STR_LIT>".format(obj.get_rotation()))<EOL>if obj.get_style() == "<STR_LIT>":<EOL><INDENT>style.append("<STR_LIT>")<EOL><DEDENT>else:<EOL><INDENT>assert obj.get_style() == "<STR_LIT>"<EOL><DEDENT>weight = obj.get_weight()<EOL>if weight in [<EOL>"<STR_LIT>",<EOL>"<STR_LIT>",<EOL>"<STR_LIT>",<EOL>"<STR_LIT>",<EOL>"<STR_LIT>",<EOL>"<STR_LIT>",<EOL>"<STR_LIT>",<EOL>] or (isinstance(weight, int) and weight > <NUM_LIT>):<EOL><INDENT>style.append("<STR_LIT>")<EOL><DEDENT>if obj.axes:<EOL><INDENT>tikz_pos = ("<STR_LIT>" + ff + "<STR_LIT:U+002C>" + ff + "<STR_LIT:)>").format(*pos)<EOL><DEDENT>else:<EOL><INDENT>tikz_pos = (<EOL>"<STR_LIT>" + ff + "<STR_LIT:!>"<EOL>"<STR_LIT>"<EOL>"<STR_LIT>"<EOL>"<STR_LIT>" + ff + "<STR_LIT:!>"<EOL>"<STR_LIT>"<EOL>).format(*pos)<EOL><DEDENT>if "<STR_LIT:\n>" in text:<EOL><INDENT>properties.append("<STR_LIT>".format(ha))<EOL>text = text.replace("<STR_LIT>", "<STR_LIT>")<EOL><DEDENT>content.append(<EOL>"<STR_LIT>".format(<EOL>tikz_pos, "<STR_LIT>".join(properties), "<STR_LIT:U+0020>".join(style + [text])<EOL>)<EOL>)<EOL>return data, content<EOL>
Paints text on the graph.
f14418:m0
def _transform_positioning(ha, va):
if ha == "<STR_LIT>" and va == "<STR_LIT>":<EOL><INDENT>return None<EOL><DEDENT>ha_mpl_to_tikz = {"<STR_LIT:right>": "<STR_LIT>", "<STR_LIT:left>": "<STR_LIT>", "<STR_LIT>": "<STR_LIT>"}<EOL>va_mpl_to_tikz = {<EOL>"<STR_LIT>": "<STR_LIT>",<EOL>"<STR_LIT>": "<STR_LIT>",<EOL>"<STR_LIT>": "<STR_LIT>",<EOL>"<STR_LIT>": "<STR_LIT>",<EOL>}<EOL>return "<STR_LIT>".format(va_mpl_to_tikz[va], ha_mpl_to_tikz[ha]).strip()<EOL>
Converts matplotlib positioning to pgf node positioning. Not quite accurate but the results are equivalent more or less.
f14418:m1
def _get_ticks(data, xy, ticks, ticklabels):
axis_options = []<EOL>pgfplots_ticks = []<EOL>pgfplots_ticklabels = []<EOL>is_label_required = False<EOL>for tick, ticklabel in zip(ticks, ticklabels):<EOL><INDENT>pgfplots_ticks.append(tick)<EOL>label = ticklabel.get_text()<EOL>if ticklabel.get_visible():<EOL><INDENT>label = mpl_backend_pgf.common_texification(label)<EOL>pgfplots_ticklabels.append(label)<EOL><DEDENT>else:<EOL><INDENT>is_label_required = True<EOL><DEDENT>if label:<EOL><INDENT>try:<EOL><INDENT>label_float = float(label.replace(u"<STR_LIT>", "<STR_LIT:->"))<EOL>is_label_required = is_label_required or (label and label_float != tick)<EOL><DEDENT>except ValueError:<EOL><INDENT>is_label_required = True<EOL><DEDENT><DEDENT><DEDENT>if data["<STR_LIT:strict>"] or is_label_required:<EOL><INDENT>if pgfplots_ticks:<EOL><INDENT>ff = data["<STR_LIT>"]<EOL>axis_options.append(<EOL>"<STR_LIT>".format(<EOL>xy, "<STR_LIT:U+002C>".join([ff.format(el) for el in pgfplots_ticks])<EOL>)<EOL>)<EOL><DEDENT>else:<EOL><INDENT>val = "<STR_LIT:{}>" if "<STR_LIT>" in xy else "<STR_LIT>"<EOL>axis_options.append("<STR_LIT>".format(xy, val))<EOL><DEDENT>if is_label_required:<EOL><INDENT>axis_options.append(<EOL>"<STR_LIT>".format(xy, "<STR_LIT:U+002C>".join(pgfplots_ticklabels))<EOL>)<EOL><DEDENT><DEDENT>return axis_options<EOL>
Gets a {'x','y'}, a number of ticks and ticks labels, and returns the necessary axis options for the given configuration.
f14420:m1
def _is_colorbar_heuristic(obj):
<EOL>try:<EOL><INDENT>aspect = float(obj.get_aspect())<EOL><DEDENT>except ValueError:<EOL><INDENT>return False<EOL><DEDENT>limit_ratio = <NUM_LIT><EOL>return (aspect >= limit_ratio and len(obj.get_xticks()) == <NUM_LIT:0>) or (<EOL>aspect <= <NUM_LIT:1.0> / limit_ratio and len(obj.get_yticks()) == <NUM_LIT:0><EOL>)<EOL>
Find out if the object is in fact a color bar.
f14420:m2
def _mpl_cmap2pgf_cmap(cmap, data):
if isinstance(cmap, mpl.colors.LinearSegmentedColormap):<EOL><INDENT>return _handle_linear_segmented_color_map(cmap, data)<EOL><DEDENT>assert isinstance(<EOL>cmap, mpl.colors.ListedColormap<EOL>), "<STR_LIT>"<EOL>return _handle_listed_color_map(cmap, data)<EOL>
Converts a color map as given in matplotlib to a color map as represented in PGFPlots.
f14420:m3
def _scale_to_int(X, max_val=None):
if max_val is None:<EOL><INDENT>X = X / _gcd_array(X)<EOL><DEDENT>else:<EOL><INDENT>X = X / max(<NUM_LIT:1> / max_val, _gcd_array(X))<EOL><DEDENT>return [int(entry) for entry in X]<EOL>
Scales the array X such that it contains only integers.
f14420:m6
def _gcd_array(X):
greatest_common_divisor = <NUM_LIT:0.0><EOL>for x in X:<EOL><INDENT>greatest_common_divisor = _gcd(greatest_common_divisor, x)<EOL><DEDENT>return greatest_common_divisor<EOL>
Return the largest real value h such that all elements in x are integer multiples of h.
f14420:m7
def _gcd(a, b):
<EOL>while a > <NUM_LIT>:<EOL><INDENT>a, b = b % a, a<EOL><DEDENT>return b<EOL>
Euclidean algorithm for calculating the GCD of two numbers a, b. This algoritm also works for real numbers: Find the greatest number h such that a and b are integer multiples of h.
f14420:m8
def _linear_interpolation(x, X, Y):
return (Y[<NUM_LIT:1>] * (x - X[<NUM_LIT:0>]) + Y[<NUM_LIT:0>] * (X[<NUM_LIT:1>] - x)) / (X[<NUM_LIT:1>] - X[<NUM_LIT:0>])<EOL>
Given two data points [X,Y], linearly interpolate those at x.
f14420:m9
def _find_associated_colorbar(obj):
for child in obj.get_children():<EOL><INDENT>try:<EOL><INDENT>cbar = child.colorbar<EOL><DEDENT>except AttributeError:<EOL><INDENT>continue<EOL><DEDENT>if cbar is not None: <EOL><INDENT>return cbar<EOL><DEDENT><DEDENT>return None<EOL>
A rather poor way of telling whether an axis has a colorbar associated: Check the next axis environment, and see if it is de facto a color bar; if yes, return the color bar object.
f14420:m10
def _try_f2i(x):
return int(x) if int(x) == x else x<EOL>
Convert losslessly float to int if possible. Used for log base: if not used, base for log scale can be "10.0" (and then printed as such by pgfplots).
f14420:m11
def __init__(self, data, obj):
self.content = []<EOL>self.is_colorbar = _is_colorbar_heuristic(obj)<EOL>if self.is_colorbar:<EOL><INDENT>return<EOL><DEDENT>self.nsubplots = <NUM_LIT:1><EOL>self.subplot_index = <NUM_LIT:0><EOL>self.is_subplot = False<EOL>if isinstance(obj, mpl.axes.Subplot):<EOL><INDENT>self._subplot(obj, data)<EOL><DEDENT>self.axis_options = []<EOL>if not obj.axison:<EOL><INDENT>self.axis_options.append("<STR_LIT>")<EOL>self.axis_options.append("<STR_LIT>")<EOL><DEDENT>title = obj.get_title()<EOL>data["<STR_LIT>"] = title<EOL>if title:<EOL><INDENT>self.axis_options.append(u"<STR_LIT>".format(title))<EOL><DEDENT>xlabel = obj.get_xlabel()<EOL>if xlabel:<EOL><INDENT>xlabel = mpl_backend_pgf.common_texification(xlabel)<EOL>self.axis_options.append(u"<STR_LIT>".format(xlabel))<EOL><DEDENT>ylabel = obj.get_ylabel()<EOL>if ylabel:<EOL><INDENT>ylabel = mpl_backend_pgf.common_texification(ylabel)<EOL>self.axis_options.append(u"<STR_LIT>".format(ylabel))<EOL><DEDENT>ff = data["<STR_LIT>"]<EOL>xlim = sorted(list(obj.get_xlim()))<EOL>self.axis_options.append(("<STR_LIT>" + ff + "<STR_LIT>" + ff).format(*xlim))<EOL>ylim = sorted(list(obj.get_ylim()))<EOL>self.axis_options.append(("<STR_LIT>" + ff + "<STR_LIT>" + ff).format(*ylim))<EOL>if obj.get_xscale() == "<STR_LIT>":<EOL><INDENT>self.axis_options.append("<STR_LIT>")<EOL>self.axis_options.append(<EOL>"<STR_LIT>".format(_try_f2i(obj.xaxis._scale.base))<EOL>)<EOL><DEDENT>if obj.get_yscale() == "<STR_LIT>":<EOL><INDENT>self.axis_options.append("<STR_LIT>")<EOL>self.axis_options.append(<EOL>"<STR_LIT>".format(_try_f2i(obj.yaxis._scale.base))<EOL>)<EOL><DEDENT>if not obj.get_axisbelow():<EOL><INDENT>self.axis_options.append("<STR_LIT>")<EOL><DEDENT>aspect = obj.get_aspect()<EOL>if aspect in ["<STR_LIT>", "<STR_LIT>"]:<EOL><INDENT>aspect_num = None <EOL><DEDENT>elif aspect == "<STR_LIT>":<EOL><INDENT>aspect_num = <NUM_LIT:1.0><EOL><DEDENT>else:<EOL><INDENT>aspect_num = float(aspect)<EOL><DEDENT>self._set_axis_dimensions(data, aspect_num, xlim, ylim)<EOL>xaxis_pos = obj.get_xaxis().label_position<EOL>if xaxis_pos == "<STR_LIT>":<EOL><INDENT>self.axis_options.append("<STR_LIT>")<EOL><DEDENT>yaxis_pos = obj.get_yaxis().label_position<EOL>if yaxis_pos == "<STR_LIT:right>":<EOL><INDENT>self.axis_options.append("<STR_LIT>")<EOL><DEDENT>self._ticks(data, obj)<EOL>self._grid(obj, data)<EOL>axcol = obj.spines["<STR_LIT>"].get_edgecolor()<EOL>data, col, _ = color.mpl_color2xcolor(data, axcol)<EOL>if col != "<STR_LIT>":<EOL><INDENT>self.axis_options.append("<STR_LIT>".format(col))<EOL><DEDENT>bgcolor = obj.get_facecolor()<EOL>data, col, _ = color.mpl_color2xcolor(data, bgcolor)<EOL>if col != "<STR_LIT>":<EOL><INDENT>self.axis_options.append("<STR_LIT>".format(col))<EOL><DEDENT>colorbar = _find_associated_colorbar(obj)<EOL>if colorbar:<EOL><INDENT>self._colorbar(colorbar, data)<EOL><DEDENT>if self.is_subplot:<EOL><INDENT>self.content.append("<STR_LIT>")<EOL><DEDENT>else:<EOL><INDENT>self.content.append("<STR_LIT>")<EOL><DEDENT>return<EOL>
Returns the PGFPlots code for an axis environment.
f14420:c0:m0
def draw_patch(data, obj):
<EOL>data, draw_options = mypath.get_draw_options(<EOL>data,<EOL>obj,<EOL>obj.get_edgecolor(),<EOL>obj.get_facecolor(),<EOL>obj.get_linestyle(),<EOL>obj.get_linewidth(),<EOL>)<EOL>if isinstance(obj, mpl.patches.Rectangle):<EOL><INDENT>return _draw_rectangle(data, obj, draw_options)<EOL><DEDENT>elif isinstance(obj, mpl.patches.Ellipse):<EOL><INDENT>return _draw_ellipse(data, obj, draw_options)<EOL><DEDENT>data, path_command, _, _ = mypath.draw_path(<EOL>data, obj.get_path(), draw_options=draw_options<EOL>)<EOL>return data, path_command<EOL>
Return the PGFPlots code for patches.
f14421:m0
def draw_patchcollection(data, obj):
content = []<EOL>try:<EOL><INDENT>ec = obj.get_edgecolor()[<NUM_LIT:0>]<EOL><DEDENT>except IndexError:<EOL><INDENT>ec = None<EOL><DEDENT>try:<EOL><INDENT>fc = obj.get_facecolor()[<NUM_LIT:0>]<EOL><DEDENT>except IndexError:<EOL><INDENT>fc = None<EOL><DEDENT>try:<EOL><INDENT>ls = obj.get_linestyle()[<NUM_LIT:0>]<EOL><DEDENT>except IndexError:<EOL><INDENT>ls = None<EOL><DEDENT>try:<EOL><INDENT>w = obj.get_linewidth()[<NUM_LIT:0>]<EOL><DEDENT>except IndexError:<EOL><INDENT>w = None<EOL><DEDENT>data, draw_options = mypath.get_draw_options(data, obj, ec, fc, ls, w)<EOL>paths = obj.get_paths()<EOL>for path in paths:<EOL><INDENT>data, cont, draw_options, is_area = mypath.draw_path(<EOL>data, path, draw_options=draw_options<EOL>)<EOL>content.append(cont)<EOL><DEDENT>if _is_in_legend(obj):<EOL><INDENT>tpe = "<STR_LIT>" if is_area else "<STR_LIT>"<EOL>do = "<STR_LIT:U+002CU+0020>".join([tpe] + draw_options) if draw_options else "<STR_LIT>"<EOL>content += [<EOL>"<STR_LIT>".format(do),<EOL>"<STR_LIT>".format(obj.get_label()),<EOL>]<EOL><DEDENT>else:<EOL><INDENT>content.append("<STR_LIT:\n>")<EOL><DEDENT>return data, content<EOL>
Returns PGFPlots code for a number of patch objects.
f14421:m1
def _draw_rectangle(data, obj, draw_options):
<EOL>label = obj.get_label()<EOL>if label == "<STR_LIT>":<EOL><INDENT>return data, []<EOL><DEDENT>handles, labels = obj.axes.get_legend_handles_labels()<EOL>labelsFound = [<EOL>label for h, label in zip(handles, labels) if obj in h.get_children()<EOL>]<EOL>if len(labelsFound) == <NUM_LIT:1>:<EOL><INDENT>label = labelsFound[<NUM_LIT:0>]<EOL><DEDENT>left_lower_x = obj.get_x()<EOL>left_lower_y = obj.get_y()<EOL>ff = data["<STR_LIT>"]<EOL>cont = (<EOL>"<STR_LIT>" + ff + "<STR_LIT:U+002C>" + ff + "<STR_LIT>"<EOL>"<STR_LIT>" + ff + "<STR_LIT:U+002C>" + ff + "<STR_LIT>"<EOL>).format(<EOL>"<STR_LIT:U+002C>".join(draw_options),<EOL>left_lower_x,<EOL>left_lower_y,<EOL>left_lower_x + obj.get_width(),<EOL>left_lower_y + obj.get_height(),<EOL>)<EOL>if label != "<STR_LIT>" and label not in data["<STR_LIT>"]:<EOL><INDENT>data["<STR_LIT>"].add(label)<EOL>cont += "<STR_LIT>".format(<EOL>"<STR_LIT:U+002C>".join(draw_options)<EOL>)<EOL>cont += "<STR_LIT>".format(label)<EOL><DEDENT>return data, cont<EOL>
Return the PGFPlots code for rectangles.
f14421:m3
def _draw_ellipse(data, obj, draw_options):
if isinstance(obj, mpl.patches.Circle):<EOL><INDENT>return _draw_circle(data, obj, draw_options)<EOL><DEDENT>x, y = obj.center<EOL>ff = data["<STR_LIT>"]<EOL>if obj.angle != <NUM_LIT:0>:<EOL><INDENT>fmt = "<STR_LIT>" + ff + "<STR_LIT>" + ff + "<STR_LIT:U+002C>" + ff + "<STR_LIT>"<EOL>draw_options.append(fmt.format(obj.angle, x, y))<EOL><DEDENT>cont = (<EOL>"<STR_LIT>"<EOL>+ ff<EOL>+ "<STR_LIT:U+002C>"<EOL>+ ff<EOL>+ "<STR_LIT>"<EOL>+ ff<EOL>+ "<STR_LIT>"<EOL>+ ff<EOL>+ "<STR_LIT>"<EOL>).format("<STR_LIT:U+002C>".join(draw_options), x, y, <NUM_LIT:0.5> * obj.width, <NUM_LIT:0.5> * obj.height)<EOL>return data, cont<EOL>
Return the PGFPlots code for ellipses.
f14421:m4
def _draw_circle(data, obj, draw_options):
x, y = obj.center<EOL>ff = data["<STR_LIT>"]<EOL>cont = ("<STR_LIT>" + ff + "<STR_LIT:U+002C>" + ff + "<STR_LIT>" + ff + "<STR_LIT>").format(<EOL>"<STR_LIT:U+002C>".join(draw_options), x, y, obj.get_radius()<EOL>)<EOL>return data, cont<EOL>
Return the PGFPlots code for circles.
f14421:m5
def mpl_color2xcolor(data, matplotlib_color):
<EOL>my_col = numpy.array(mpl.colors.ColorConverter().to_rgba(matplotlib_color))<EOL>if my_col[-<NUM_LIT:1>] == <NUM_LIT:0.0>:<EOL><INDENT>return data, "<STR_LIT:none>", my_col<EOL><DEDENT>xcol = None<EOL>available_colors = {<EOL>"<STR_LIT>": numpy.array([<NUM_LIT:1>, <NUM_LIT:1>, <NUM_LIT:1>]),<EOL>"<STR_LIT>": numpy.array([<NUM_LIT>, <NUM_LIT>, <NUM_LIT>]),<EOL>"<STR_LIT>": numpy.array([<NUM_LIT:0.5>, <NUM_LIT:0.5>, <NUM_LIT:0.5>]),<EOL>"<STR_LIT>": numpy.array([<NUM_LIT>, <NUM_LIT>, <NUM_LIT>]),<EOL>"<STR_LIT>": numpy.array([<NUM_LIT:0>, <NUM_LIT:0>, <NUM_LIT:0>]),<EOL>"<STR_LIT>": numpy.array([<NUM_LIT:1>, <NUM_LIT:0>, <NUM_LIT:0>]),<EOL>"<STR_LIT>": numpy.array([<NUM_LIT:0>, <NUM_LIT:1>, <NUM_LIT:0>]),<EOL>"<STR_LIT>": numpy.array([<NUM_LIT:0>, <NUM_LIT:0>, <NUM_LIT:1>]),<EOL>"<STR_LIT>": numpy.array([<NUM_LIT>, <NUM_LIT:0.5>, <NUM_LIT>]),<EOL>"<STR_LIT>": numpy.array([<NUM_LIT>, <NUM_LIT:1>, <NUM_LIT:0>]),<EOL>"<STR_LIT>": numpy.array([<NUM_LIT:1>, <NUM_LIT:0.5>, <NUM_LIT:0>]),<EOL>"<STR_LIT>": numpy.array([<NUM_LIT:1>, <NUM_LIT>, <NUM_LIT>]),<EOL>"<STR_LIT>": numpy.array([<NUM_LIT>, <NUM_LIT:0>, <NUM_LIT>]),<EOL>"<STR_LIT>": numpy.array([<NUM_LIT:0>, <NUM_LIT:0.5>, <NUM_LIT:0.5>]),<EOL>"<STR_LIT>": numpy.array([<NUM_LIT:0.5>, <NUM_LIT:0>, <NUM_LIT:0.5>]),<EOL>}<EOL>available_colors.update(data["<STR_LIT>"])<EOL>for name, rgb in available_colors.items():<EOL><INDENT>if all(my_col[:<NUM_LIT:3>] == rgb):<EOL><INDENT>xcol = name<EOL>return data, xcol, my_col<EOL><DEDENT><DEDENT>for name, rgb in available_colors.items():<EOL><INDENT>if name == "<STR_LIT>":<EOL><INDENT>continue<EOL><DEDENT>if rgb[<NUM_LIT:0>] != <NUM_LIT:0.0>:<EOL><INDENT>alpha = my_col[<NUM_LIT:0>] / rgb[<NUM_LIT:0>]<EOL><DEDENT>elif rgb[<NUM_LIT:1>] != <NUM_LIT:0.0>:<EOL><INDENT>alpha = my_col[<NUM_LIT:1>] / rgb[<NUM_LIT:1>]<EOL><DEDENT>else:<EOL><INDENT>assert rgb[<NUM_LIT:2>] != <NUM_LIT:0.0><EOL>alpha = my_col[<NUM_LIT:2>] / rgb[<NUM_LIT:2>]<EOL><DEDENT>if all(my_col[:<NUM_LIT:3>] == alpha * rgb) and <NUM_LIT:0.0> < alpha < <NUM_LIT:1.0>:<EOL><INDENT>xcol = name + ("<STR_LIT>".format(alpha * <NUM_LIT:100>))<EOL>return data, xcol, my_col<EOL><DEDENT><DEDENT>xcol = "<STR_LIT>" + str(len(data["<STR_LIT>"]))<EOL>data["<STR_LIT>"][xcol] = my_col[:<NUM_LIT:3>]<EOL>return data, xcol, my_col<EOL>
Translates a matplotlib color specification into a proper LaTeX xcolor.
f14422:m0
def print_tree(obj, indent="<STR_LIT>"):
if isinstance(obj, matplotlib.text.Text):<EOL><INDENT>print(indent, type(obj).__name__, '<STR_LIT>'.format(obj.get_text()))<EOL><DEDENT>else:<EOL><INDENT>print(indent, type(obj).__name__)<EOL><DEDENT>for child in obj.get_children():<EOL><INDENT>print_tree(child, indent + "<STR_LIT:U+0020>")<EOL><DEDENT>return<EOL>
Recursively prints the tree structure of the matplotlib object.
f14457:m0
def merge_dict(d1, d2):
for k,v2 in list(d2.items()):<EOL><INDENT>v1 = d1.get(k) <EOL>if ( isinstance(v1, collections.Mapping) and<EOL>isinstance(v2, collections.Mapping) ):<EOL><INDENT>merge_dict(v1, v2)<EOL><DEDENT>else:<EOL><INDENT>d1[k] = v2<EOL><DEDENT><DEDENT>
Modifies d1 in-place to contain values from d2. If any value in d1 is a dictionary (or dict-like), *and* the corresponding value in d2 is also a dictionary, then merge them in-place.
f14487:m1
def _args_from_interpreter_flags():
flag_opt_map = {<EOL>'<STR_LIT>': '<STR_LIT:d>',<EOL>'<STR_LIT>': '<STR_LIT:O>',<EOL>'<STR_LIT>': '<STR_LIT:B>',<EOL>'<STR_LIT>': '<STR_LIT:s>',<EOL>'<STR_LIT>': '<STR_LIT:S>',<EOL>'<STR_LIT>': '<STR_LIT:E>',<EOL>'<STR_LIT>': '<STR_LIT:v>',<EOL>'<STR_LIT>': '<STR_LIT:b>',<EOL>'<STR_LIT>': '<STR_LIT:R>',<EOL>'<STR_LIT>': '<STR_LIT:3>',<EOL>}<EOL>args = []<EOL>for flag, opt in list(flag_opt_map.items()):<EOL><INDENT>v = getattr(sys.flags, flag)<EOL>if v > <NUM_LIT:0>:<EOL><INDENT>args.append('<STR_LIT:->' + opt * v)<EOL><DEDENT><DEDENT>for opt in sys.warnoptions:<EOL><INDENT>args.append('<STR_LIT>' + opt)<EOL><DEDENT>return args<EOL>
Return a list of command-line arguments reproducing the current settings in sys.flags and sys.warnoptions.
f14490:m2
def call(*popenargs, **kwargs):
return Popen(*popenargs, **kwargs).wait()<EOL>
Run command with arguments. Wait for command to complete, then return the returncode attribute. The arguments are the same as for the Popen constructor. Example: retcode = call(["ls", "-l"])
f14490:m3
def check_call(*popenargs, **kwargs):
retcode = call(*popenargs, **kwargs)<EOL>if retcode:<EOL><INDENT>cmd = kwargs.get("<STR_LIT:args>")<EOL>if cmd is None:<EOL><INDENT>cmd = popenargs[<NUM_LIT:0>]<EOL><DEDENT>raise CalledProcessError(retcode, cmd)<EOL><DEDENT>return <NUM_LIT:0><EOL>
Run command with arguments. Wait for command to complete. If the exit code was zero then return, otherwise raise CalledProcessError. The CalledProcessError object will have the return code in the returncode attribute. The arguments are the same as for the Popen constructor. Example: check_call(["ls", "-l"])
f14490:m4
def check_output(*popenargs, **kwargs):
if '<STR_LIT>' in kwargs:<EOL><INDENT>raise ValueError('<STR_LIT>')<EOL><DEDENT>process = Popen(stdout=PIPE, *popenargs, **kwargs)<EOL>output, unused_err = process.communicate()<EOL>retcode = process.poll()<EOL>if retcode:<EOL><INDENT>cmd = kwargs.get("<STR_LIT:args>")<EOL>if cmd is None:<EOL><INDENT>cmd = popenargs[<NUM_LIT:0>]<EOL><DEDENT>raise CalledProcessError(retcode, cmd, output=output)<EOL><DEDENT>return output<EOL>
r"""Run command with arguments and return its output as a byte string. If the exit code was non-zero it raises a CalledProcessError. The CalledProcessError object will have the return code in the returncode attribute and output in the output attribute. The arguments are the same as for the Popen constructor. Example: >>> check_output(["ls", "-l", "/dev/null"]) 'crw-rw-rw- 1 root root 1, 3 Oct 18 2007 /dev/null\n' The stdout argument is not allowed as it is used internally. To capture standard error in the result, use stderr=STDOUT. >>> check_output(["/bin/sh", "-c", ... "ls -l non_existent_file ; exit 0"], ... stderr=STDOUT) 'ls: non_existent_file: No such file or directory\n'
f14490:m5
def list2cmdline(seq):
<EOL>result = []<EOL>needquote = False<EOL>for arg in seq:<EOL><INDENT>bs_buf = []<EOL>if result:<EOL><INDENT>result.append('<STR_LIT:U+0020>')<EOL><DEDENT>needquote = ("<STR_LIT:U+0020>" in arg) or ("<STR_LIT:\t>" in arg) or not arg<EOL>if needquote:<EOL><INDENT>result.append('<STR_LIT:">')<EOL><DEDENT>for c in arg:<EOL><INDENT>if c == '<STR_LIT:\\>':<EOL><INDENT>bs_buf.append(c)<EOL><DEDENT>elif c == '<STR_LIT:">':<EOL><INDENT>result.append('<STR_LIT:\\>' * len(bs_buf)*<NUM_LIT:2>)<EOL>bs_buf = []<EOL>result.append('<STR_LIT>')<EOL><DEDENT>else:<EOL><INDENT>if bs_buf:<EOL><INDENT>result.extend(bs_buf)<EOL>bs_buf = []<EOL><DEDENT>result.append(c)<EOL><DEDENT><DEDENT>if bs_buf:<EOL><INDENT>result.extend(bs_buf)<EOL><DEDENT>if needquote:<EOL><INDENT>result.extend(bs_buf)<EOL>result.append('<STR_LIT:">')<EOL><DEDENT><DEDENT>return '<STR_LIT>'.join(result)<EOL>
Translate a sequence of arguments into a command line string, using the same rules as the MS C runtime: 1) Arguments are delimited by white space, which is either a space or a tab. 2) A string surrounded by double quotation marks is interpreted as a single argument, regardless of white space contained within. A quoted string can be embedded in an argument. 3) A double quotation mark preceded by a backslash is interpreted as a literal double quotation mark. 4) Backslashes are interpreted literally, unless they immediately precede a double quotation mark. 5) If backslashes immediately precede a double quotation mark, every pair of backslashes is interpreted as a literal backslash. If the number of backslashes is odd, the last backslash escapes the next double quotation mark as described in rule 3.
f14490:m6
def __init__(self, args, bufsize=<NUM_LIT:0>, executable=None,<EOL>stdin=None, stdout=None, stderr=None,<EOL>preexec_fn=None, close_fds=False, shell=False,<EOL>cwd=None, env=None, universal_newlines=False,<EOL>startupinfo=None, creationflags=<NUM_LIT:0>):
_cleanup()<EOL>self._child_created = False<EOL>if not isinstance(bufsize, int):<EOL><INDENT>raise TypeError("<STR_LIT>")<EOL><DEDENT>if mswindows:<EOL><INDENT>if preexec_fn is not None:<EOL><INDENT>raise ValueError("<STR_LIT>"<EOL>"<STR_LIT>")<EOL><DEDENT>if close_fds and (stdin is not None or stdout is not None or<EOL>stderr is not None):<EOL><INDENT>raise ValueError("<STR_LIT>"<EOL>"<STR_LIT>")<EOL><DEDENT><DEDENT>else:<EOL><INDENT>if startupinfo is not None:<EOL><INDENT>raise ValueError("<STR_LIT>"<EOL>"<STR_LIT>")<EOL><DEDENT>if creationflags != <NUM_LIT:0>:<EOL><INDENT>raise ValueError("<STR_LIT>"<EOL>"<STR_LIT>")<EOL><DEDENT><DEDENT>self.stdin = None<EOL>self.stdout = None<EOL>self.stderr = None<EOL>self.pid = None<EOL>self.returncode = None<EOL>self.universal_newlines = universal_newlines<EOL>(p2cread, p2cwrite,<EOL>c2pread, c2pwrite,<EOL>errread, errwrite), to_close = self._get_handles(stdin, stdout, stderr)<EOL>try:<EOL><INDENT>self._execute_child(args, executable, preexec_fn, close_fds,<EOL>cwd, env, universal_newlines,<EOL>startupinfo, creationflags, shell, to_close,<EOL>p2cread, p2cwrite,<EOL>c2pread, c2pwrite,<EOL>errread, errwrite)<EOL><DEDENT>except Exception:<EOL><INDENT>exc_type, exc_value, exc_trace = sys.exc_info()<EOL>for fd in to_close:<EOL><INDENT>try:<EOL><INDENT>if mswindows:<EOL><INDENT>fd.Close()<EOL><DEDENT>else:<EOL><INDENT>os.close(fd)<EOL><DEDENT><DEDENT>except EnvironmentError:<EOL><INDENT>pass<EOL><DEDENT><DEDENT>raise exc_type(exc_value).with_traceback(exc_trace)<EOL><DEDENT>if mswindows:<EOL><INDENT>if p2cwrite is not None:<EOL><INDENT>p2cwrite = msvcrt.open_osfhandle(p2cwrite.Detach(), <NUM_LIT:0>)<EOL><DEDENT>if c2pread is not None:<EOL><INDENT>c2pread = msvcrt.open_osfhandle(c2pread.Detach(), <NUM_LIT:0>)<EOL><DEDENT>if errread is not None:<EOL><INDENT>errread = msvcrt.open_osfhandle(errread.Detach(), <NUM_LIT:0>)<EOL><DEDENT><DEDENT>if p2cwrite is not None:<EOL><INDENT>self.stdin = os.fdopen(p2cwrite, '<STR_LIT:wb>', bufsize)<EOL><DEDENT>if c2pread is not None:<EOL><INDENT>if universal_newlines:<EOL><INDENT>self.stdout = os.fdopen(c2pread, '<STR_LIT>', bufsize)<EOL><DEDENT>else:<EOL><INDENT>self.stdout = os.fdopen(c2pread, '<STR_LIT:rb>', bufsize)<EOL><DEDENT><DEDENT>if errread is not None:<EOL><INDENT>if universal_newlines:<EOL><INDENT>self.stderr = os.fdopen(errread, '<STR_LIT>', bufsize)<EOL><DEDENT>else:<EOL><INDENT>self.stderr = os.fdopen(errread, '<STR_LIT:rb>', bufsize)<EOL><DEDENT><DEDENT>
Create new Popen instance.
f14490:c1:m0
def communicate(self, input=None):
<EOL>if [self.stdin, self.stdout, self.stderr].count(None) >= <NUM_LIT:2>:<EOL><INDENT>stdout = None<EOL>stderr = None<EOL>if self.stdin:<EOL><INDENT>if input:<EOL><INDENT>try:<EOL><INDENT>self.stdin.write(input)<EOL><DEDENT>except IOError as e:<EOL><INDENT>if e.errno != errno.EPIPE and e.errno != errno.EINVAL:<EOL><INDENT>raise<EOL><DEDENT><DEDENT><DEDENT>self.stdin.close()<EOL><DEDENT>elif self.stdout:<EOL><INDENT>stdout = _eintr_retry_call(self.stdout.read)<EOL>self.stdout.close()<EOL><DEDENT>elif self.stderr:<EOL><INDENT>stderr = _eintr_retry_call(self.stderr.read)<EOL>self.stderr.close()<EOL><DEDENT>self.wait()<EOL>return (stdout, stderr)<EOL><DEDENT>return self._communicate(input)<EOL>
Interact with process: Send data to stdin. Read data from stdout and stderr, until end-of-file is reached. Wait for process to terminate. The optional input argument should be a string to be sent to the child process, or None, if no data should be sent to the child. communicate() returns a tuple (stdout, stderr).
f14490:c1:m3
def from_html(html_code, **kwargs):
parser = TableHandler(**kwargs)<EOL>parser.feed(html_code)<EOL>return parser.tables<EOL>
Generates a list of PrettyTables from a string of HTML code. Each <table> in the HTML becomes one PrettyTable object.
f14504:m5
def from_html_one(html_code, **kwargs):
tables = from_html(html_code, **kwargs)<EOL>try:<EOL><INDENT>assert len(tables) == <NUM_LIT:1><EOL><DEDENT>except AssertionError:<EOL><INDENT>raise Exception("<STR_LIT>")<EOL><DEDENT>return tables[<NUM_LIT:0>]<EOL>
Generates a PrettyTables from a string of HTML code which contains only a single <table>
f14504:m6
def __init__(self, field_names=None, **kwargs):
self.encoding = kwargs.get("<STR_LIT>", "<STR_LIT>")<EOL>self._field_names = []<EOL>self._align = {}<EOL>self._valign = {}<EOL>self._max_width = {}<EOL>self._rows = []<EOL>if field_names:<EOL><INDENT>self.field_names = field_names<EOL><DEDENT>else:<EOL><INDENT>self._widths = []<EOL><DEDENT>self._options = "<STR_LIT>".split()<EOL>self._options.extend("<STR_LIT>".split())<EOL>self._options.extend("<STR_LIT>".split())<EOL>for option in self._options:<EOL><INDENT>if option in kwargs:<EOL><INDENT>self._validate_option(option, kwargs[option])<EOL><DEDENT>else:<EOL><INDENT>kwargs[option] = None<EOL><DEDENT><DEDENT>self._start = kwargs["<STR_LIT:start>"] or <NUM_LIT:0><EOL>self._end = kwargs["<STR_LIT:end>"] or None<EOL>self._fields = kwargs["<STR_LIT>"] or None<EOL>if kwargs["<STR_LIT>"] in (True, False):<EOL><INDENT>self._header = kwargs["<STR_LIT>"]<EOL><DEDENT>else:<EOL><INDENT>self._header = True<EOL><DEDENT>self._header_style = kwargs["<STR_LIT>"] or None<EOL>if kwargs["<STR_LIT>"] in (True, False):<EOL><INDENT>self._border = kwargs["<STR_LIT>"]<EOL><DEDENT>else:<EOL><INDENT>self._border = True<EOL><DEDENT>self._hrules = kwargs["<STR_LIT>"] or FRAME<EOL>self._vrules = kwargs["<STR_LIT>"] or ALL<EOL>self._sortby = kwargs["<STR_LIT>"] or None<EOL>if kwargs["<STR_LIT>"] in (True, False):<EOL><INDENT>self._reversesort = kwargs["<STR_LIT>"]<EOL><DEDENT>else:<EOL><INDENT>self._reversesort = False<EOL><DEDENT>self._sort_key = kwargs["<STR_LIT>"] or (lambda x: x)<EOL>self._int_format = kwargs["<STR_LIT>"] or {}<EOL>self._float_format = kwargs["<STR_LIT>"] or {}<EOL>self._padding_width = kwargs["<STR_LIT>"] or <NUM_LIT:1><EOL>self._left_padding_width = kwargs["<STR_LIT>"] or None<EOL>self._right_padding_width = kwargs["<STR_LIT>"] or None<EOL>self._vertical_char = kwargs["<STR_LIT>"] or self._unicode("<STR_LIT:|>")<EOL>self._horizontal_char = kwargs["<STR_LIT>"] or self._unicode("<STR_LIT:->")<EOL>self._junction_char = kwargs["<STR_LIT>"] or self._unicode("<STR_LIT:+>")<EOL>if kwargs["<STR_LIT>"] in (True, False):<EOL><INDENT>self._print_empty = kwargs["<STR_LIT>"]<EOL><DEDENT>else:<EOL><INDENT>self._print_empty = True<EOL><DEDENT>self._format = kwargs["<STR_LIT>"] or False<EOL>self._xhtml = kwargs["<STR_LIT>"] or False<EOL>self._attributes = kwargs["<STR_LIT>"] or {}<EOL>
Return a new PrettyTable instance Arguments: encoding - Unicode encoding scheme used to decode any encoded input field_names - list or tuple of field names fields - list or tuple of field names to include in displays start - index of first data row to include in output end - index of last data row to include in output PLUS ONE (list slice style) header - print a header showing field names (True or False) header_style - stylisation to apply to field names in header ("cap", "title", "upper", "lower" or None) border - print a border around the table (True or False) hrules - controls printing of horizontal rules after rows. Allowed values: FRAME, HEADER, ALL, NONE vrules - controls printing of vertical rules between columns. Allowed values: FRAME, ALL, NONE int_format - controls formatting of integer data float_format - controls formatting of floating point data padding_width - number of spaces on either side of column data (only used if left and right paddings are None) left_padding_width - number of spaces on left hand side of column data right_padding_width - number of spaces on right hand side of column data vertical_char - single character string used to draw vertical lines horizontal_char - single character string used to draw horizontal lines junction_char - single character string used to draw line junctions sortby - name of field to sort rows by sort_key - sorting key function, applied to data points before sorting valign - default valign for each row (None, "t", "m" or "b") reversesort - True or False to sort in descending or ascending order
f14504:c0:m0
def _get_fields(self):
return self._fields<EOL>
List or tuple of field names to include in displays Arguments: fields - list or tuple of field names to include in displays
f14504:c0:m30
def _get_start(self):
return self._start<EOL>
Start index of the range of rows to print Arguments: start - index of first data row to include in output
f14504:c0:m32
def _get_end(self):
return self._end<EOL>
End index of the range of rows to print Arguments: end - index of last data row to include in output PLUS ONE (list slice style)
f14504:c0:m34
def _get_sortby(self):
return self._sortby<EOL>
Name of field by which to sort rows Arguments: sortby - field name to sort by
f14504:c0:m36
def _get_reversesort(self):
return self._reversesort<EOL>
Controls direction of sorting (ascending vs descending) Arguments: reveresort - set to True to sort by descending order, or False to sort by ascending order
f14504:c0:m38
def _get_sort_key(self):
return self._sort_key<EOL>
Sorting key function, applied to data points before sorting Arguments: sort_key - a function which takes one argument and returns something to be sorted
f14504:c0:m40