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. ...
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. ...
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,...
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>),...
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 po...
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_LI...
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 (...
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>'<S...
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...
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><DED...
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 latti...
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>, <...
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` node...
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...
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 ...
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 * <...
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 Pe...
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 =...
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_...
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>...
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" coord...
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): retu...
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" ...
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>edgeli...
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...
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>un...
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 : N...
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...
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, ...}. Coord...
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,...
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 : flo...
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...
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.) Scal...
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. lin...
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 ---------- ...
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, offse...
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. ...
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...
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...
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><E...
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 : fl...
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 {}) ...
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 ---------- ...
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, coordin...
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. ...
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(si...
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...
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>i...
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>"...
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>ret...
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, yda...
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 co...
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_L...
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=cl...
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_exis...
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 ...
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>...
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_xcolo...
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(lines...
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>ma...
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=Non...
<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><INDEN...
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/PG...
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>r...
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...
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 + "<S...
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....
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>...
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>": "<S...
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)<...
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_...
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....
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><DED...
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 = labelsF...
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....
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....
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>'...
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...
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[<N...
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 cons...
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:<E...
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...
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...
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><IN...
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. communica...
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>".s...
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 ...
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