text_prompt stringlengths 157 13.1k | code_prompt stringlengths 7 19.8k ⌀ |
|---|---|
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def change_tunnel_ad_url(self):
''' Change tunnel ad url. '''
if self.is_open:
self.close()
req = requests.delete('https://api.psiturk.org/api/tunnel/',
auth=(self.access_key, self.secret_key))
# the request content here actually will include the tunnel_hostname
# if needed or wanted.
if req.status_code in [401, 403, 500]:
print(req.content)
return False |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def traveling_salesman(G, sampler=None, lagrange=2, weight='weight', **sampler_args):
"""Returns an approximate minimum traveling salesperson route. Defines a QUBO with ground states corresponding to the minimum routes and uses the sampler to sample from it. A route is a cycle in the graph that reaches each node exactly once. A minimum route is a route with the smallest total edge weight. Parameters G : NetworkX graph The graph on which to find a minimum traveling salesperson route. This should be a complete graph with non-zero weights on every edge. sampler : A binary quadratic model sampler. A sampler is a process that samples from low energy states in models defined by an Ising equation or a Quadratic Unconstrained Binary Optimization Problem (QUBO). A sampler is expected to have a 'sample_qubo' and 'sample_ising' method. A sampler is expected to return an iterable of samples, in order of increasing energy. If no sampler is provided, one must be provided using the `set_default_sampler` function. lagrange : optional (default 2) Lagrange parameter to weight constraints (visit every city once) versus objective (shortest distance route). weight : optional (default 'weight') The name of the edge attribute containing the weight. sampler_args : Additional keyword parameters are passed to the sampler. Returns ------- route : list List of nodes in order to be visited on a route Examples -------- This example uses a `dimod <https://github.com/dwavesystems/dimod>`_ sampler to find a minimum route in a five-cities problem. [2, 1, 0, 3] Notes ----- Samplers by their nature may not return the optimal solution. This function does not attempt to confirm the quality of the returned sample. """ |
# Get a QUBO representation of the problem
Q = traveling_salesman_qubo(G, lagrange, weight)
# use the sampler to find low energy states
response = sampler.sample_qubo(Q, **sampler_args)
# we want the lowest energy sample, in order by stop number
sample = next(iter(response))
route = []
for entry in sample:
if sample[entry] > 0:
route.append(entry)
route.sort(key=lambda x: x[1])
return list((x[0] for x in route)) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def traveling_salesman_qubo(G, lagrange=2, weight='weight'):
"""Return the QUBO with ground states corresponding to a minimum TSP route. If :math:`|G|` is the number of nodes in the graph, the resulting qubo will have: * :math:`|G|^2` variables/nodes * :math:`2 |G|^2 (|G| - 1)` interactions/edges Parameters G : NetworkX graph A complete graph in which each edge has a attribute giving its weight. lagrange : number, optional (default 2) Lagrange parameter to weight constraints (no edges within set) versus objective (largest set possible). weight : optional (default 'weight') The name of the edge attribute containing the weight. Returns ------- QUBO : dict The QUBO with ground states corresponding to a minimum travelling salesperson route. """ |
N = G.number_of_nodes()
# some input checking
if N in (1, 2) or len(G.edges) != N*(N-1)//2:
msg = "graph must be a complete graph with at least 3 nodes or empty"
raise ValueError(msg)
# Creating the QUBO
Q = defaultdict(float)
# Constraint that each row has exactly one 1
for node in G:
for pos_1 in range(N):
Q[((node, pos_1), (node, pos_1))] -= lagrange
for pos_2 in range(pos_1+1, N):
Q[((node, pos_1), (node, pos_2))] += 2.0*lagrange
# Constraint that each col has exactly one 1
for pos in range(N):
for node_1 in G:
Q[((node_1, pos), (node_1, pos))] -= lagrange
for node_2 in set(G)-{node_1}:
Q[((node_1, pos), (node_2, pos))] += 2.0*lagrange
# Objective that minimizes distance
for u, v in itertools.combinations(G.nodes, 2):
for pos in range(N):
nextpos = (pos + 1) % N
# going from u -> v
Q[((u, pos), (v, nextpos))] += G[u][v][weight]
# going from v -> u
Q[((v, pos), (u, nextpos))] += G[u][v][weight]
return Q |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def markov_network(potentials):
"""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 -------- -1 .. _Markov Random Field: https://en.wikipedia.org/wiki/Markov_random_field """ |
G = nx.Graph()
G.name = 'markov_network({!r})'.format(potentials)
# we use 'clique' because the keys of potentials can be either nodes or
# edges, but in either case they are fully connected.
for clique, phis in potentials.items():
num_vars = len(clique)
# because this data potentially wont be used for a while, let's do some
# input checking now and save some debugging issues later
if not isinstance(phis, abc.Mapping):
raise TypeError("phis should be a dict")
elif not all(config in phis for config in itertools.product((0, 1), repeat=num_vars)):
raise ValueError("not all potentials provided for {!r}".format(clique))
if num_vars == 1:
u, = clique
G.add_node(u, potential=phis)
elif num_vars == 2:
u, v = clique
# in python<=3.5 the edge order might not be consistent so we store
# the relevant order of the variables relative to the potentials
G.add_edge(u, v, potential=phis, order=(u, v))
else:
# developer note: in principle supporting larger cliques can be done
# using higher-order, but it would make the use of networkx graphs
# far more difficult
raise ValueError("Only supports cliques up to size 2")
return G |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def maximum_cut(G, sampler=None, **sampler_args):
"""Returns an approximate maximum cut. Defines an Ising problem with ground states corresponding to a maximum cut and uses the sampler to sample from it. A maximum cut is a subset S of the vertices of G such that the number of edges between S and the complementary subset is as large as possible. Parameters G : NetworkX graph The graph on which to find a maximum cut. sampler A binary quadratic model sampler. A sampler is a process that samples from low energy states in models defined by an Ising equation or a Quadratic Unconstrained Binary Optimization Problem (QUBO). A sampler is expected to have a 'sample_qubo' and 'sample_ising' method. A sampler is expected to return an iterable of samples, in order of increasing energy. If no sampler is provided, one must be provided using the `set_default_sampler` function. sampler_args Additional keyword parameters are passed to the sampler. Returns ------- S : set A maximum cut of G. Example ------- This example uses a sampler from `dimod <https://github.com/dwavesystems/dimod>`_ to find a maximum cut for a graph of a Chimera unit cell created using the `chimera_graph()` function. Notes ----- Samplers by their nature may not return the optimal solution. This function does not attempt to confirm the quality of the returned sample. """ |
# In order to form the Ising problem, we want to increase the
# energy by 1 for each edge between two nodes of the same color.
# The linear biases can all be 0.
h = {v: 0. for v in G}
J = {(u, v): 1 for u, v in G.edges}
# draw the lowest energy sample from the sampler
response = sampler.sample_ising(h, J, **sampler_args)
sample = next(iter(response))
return set(v for v in G if sample[v] >= 0) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def weighted_maximum_cut(G, sampler=None, **sampler_args):
"""Returns an approximate weighted maximum cut. Defines an Ising problem with ground states corresponding to a weighted maximum cut and uses the sampler to sample from it. A weighted maximum cut is a subset S of the vertices of G that maximizes the sum of the edge weights between S and its complementary subset. Parameters G : NetworkX graph The graph on which to find a weighted maximum cut. Each edge in G should have a numeric `weight` attribute. sampler A binary quadratic model sampler. A sampler is a process that samples from low energy states in models defined by an Ising equation or a Quadratic Unconstrained Binary Optimization Problem (QUBO). A sampler is expected to have a 'sample_qubo' and 'sample_ising' method. A sampler is expected to return an iterable of samples, in order of increasing energy. If no sampler is provided, one must be provided using the `set_default_sampler` function. sampler_args Additional keyword parameters are passed to the sampler. Returns ------- S : set A maximum cut of G. Example ------- This example uses a sampler from `dimod <https://github.com/dwavesystems/dimod>`_ to find a weighted maximum cut for a graph of a Chimera unit cell. The graph is created using the `chimera_graph()` function with weights added to all its edges such that those incident to nodes {6, 7} have weight -1 while the others are +1. A weighted maximum cut should cut as many of the latter and few of the former as possible. {4, 5} Notes ----- Samplers by their nature may not return the optimal solution. This function does not attempt to confirm the quality of the returned sample. """ |
# In order to form the Ising problem, we want to increase the
# energy by 1 for each edge between two nodes of the same color.
# The linear biases can all be 0.
h = {v: 0. for v in G}
try:
J = {(u, v): G[u][v]['weight'] for u, v in G.edges}
except KeyError:
raise DWaveNetworkXException("edges must have 'weight' attribute")
# draw the lowest energy sample from the sampler
response = sampler.sample_ising(h, J, **sampler_args)
sample = next(iter(response))
return set(v for v in G if sample[v] >= 0) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def get_pegasus_to_nice_fn(*args, **kwargs):
""" 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. """ |
if args or kwargs:
warnings.warn("Deprecation warning: get_pegasus_to_nice_fn does not need / use parameters anymore")
def p2n0(u, w, k, z): return (0, w-1 if u else z, z if u else w, u, k-4 if u else k-4)
def p2n1(u, w, k, z): return (1, w-1 if u else z, z if u else w, u, k if u else k-8)
def p2n2(u, w, k, z): return (2, w if u else z, z if u else w-1, u, k-8 if u else k)
def p2n(u, w, k, z): return [p2n0, p2n1, p2n2][(2-u-(2*u-1)*(k//4)) % 3](u, w, k, z)
return p2n |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def get_nice_to_pegasus_fn(*args, **kwargs):
""" 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 """ |
if args or kwargs:
warnings.warn("Deprecation warning: get_pegasus_to_nice_fn does not need / use parameters anymore")
def c2p0(y, x, u, k): return (u, y+1 if u else x, 4+k if u else 4+k, x if u else y)
def c2p1(y, x, u, k): return (u, y+1 if u else x, k if u else 8+k, x if u else y)
def c2p2(y, x, u, k): return (u, y if u else x + 1, 8+k if u else k, x if u else y)
def n2p(t, y, x, u, k): return [c2p0, c2p1, c2p2][t](y, x, u, k)
return n2p |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def tuple(self, r):
""" 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 """ |
m, m1 = self.args
r, z = divmod(r, m1)
r, k = divmod(r, 12)
u, w = divmod(r, m)
return u, w, k, z |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def ints(self, qlist):
""" 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 """ |
m, m1 = self.args
return (((m * u + w) * 12 + k) * m1 + z for (u, w, k, z) in qlist) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def tuples(self, rlist):
""" 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 """ |
m, m1 = self.args
for r in rlist:
r, z = divmod(r, m1)
r, k = divmod(r, 12)
u, w = divmod(r, m)
yield u, w, k, z |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def __pair_repack(self, f, plist):
""" 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) """ |
ulist = f(u for p in plist for u in p)
for u in ulist:
v = next(ulist)
yield u, v |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def sample_markov_network(MN, sampler=None, fixed_variables=None, return_sampleset=False, **sampler_args):
"""Samples from a markov network using the provided sampler. Parameters G : NetworkX graph A Markov Network as returned by :func:`.markov_network` sampler A binary quadratic model sampler. A sampler is a process that samples from low energy states in models defined by an Ising equation or a Quadratic Unconstrained Binary Optimization Problem (QUBO). A sampler is expected to have a 'sample_qubo' and 'sample_ising' method. A sampler is expected to return an iterable of samples, in order of increasing energy. If no sampler is provided, one must be provided using the `set_default_sampler` function. fixed_variables : dict A dictionary of variable assignments to be fixed in the markov network. return_sampleset : bool (optional, default=False) If True, returns a :obj:`dimod.SampleSet` rather than a list of samples. **sampler_args Additional keyword parameters are passed to the sampler. Returns ------- samples : list[dict]/:obj:`dimod.SampleSet` A list of samples ordered from low-to-high energy or a sample set. Examples -------- {'a': 0, 'b': 0} Sample(sample={'a': 0, 'b': 0}, energy=-1.0, num_occurrences=1) {'a': 0, 'c': 0, 'b': 0} Notes ----- Samplers by their nature may not return the optimal solution. This function does not attempt to confirm the quality of the returned sample. """ |
bqm = markov_network_bqm(MN)
# use the FixedVar
fv_sampler = dimod.FixedVariableComposite(sampler)
sampleset = fv_sampler.sample(bqm, fixed_variables=fixed_variables,
**sampler_args)
if return_sampleset:
return sampleset
else:
return list(map(dict, sampleset.samples())) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def markov_network_bqm(MN):
"""Construct a binary quadratic model for a markov network. Parameters G : NetworkX graph A Markov Network as returned by :func:`.markov_network` Returns ------- bqm : :obj:`dimod.BinaryQuadraticModel` A binary quadratic model. """ |
bqm = dimod.BinaryQuadraticModel.empty(dimod.BINARY)
# the variable potentials
for v, ddict in MN.nodes(data=True, default=None):
potential = ddict.get('potential', None)
if potential is None:
continue
# for single nodes we don't need to worry about order
phi0 = potential[(0,)]
phi1 = potential[(1,)]
bqm.add_variable(v, phi1 - phi0)
bqm.add_offset(phi0)
# the interaction potentials
for u, v, ddict in MN.edges(data=True, default=None):
potential = ddict.get('potential', None)
if potential is None:
continue
# in python<=3.5 the edge order might not be consistent so we use the
# one that was stored
order = ddict['order']
u, v = order
phi00 = potential[(0, 0)]
phi01 = potential[(0, 1)]
phi10 = potential[(1, 0)]
phi11 = potential[(1, 1)]
bqm.add_variable(u, phi10 - phi00)
bqm.add_variable(v, phi01 - phi00)
bqm.add_interaction(u, v, phi11 - phi10 - phi01 + phi00)
bqm.add_offset(phi00)
return bqm |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def chimera_layout(G, scale=1., center=None, dim=2):
"""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 -------- """ |
if not isinstance(G, nx.Graph):
empty_graph = nx.Graph()
empty_graph.add_edges_from(G)
G = empty_graph
# now we get chimera coordinates for the translation
# first, check if we made it
if G.graph.get("family") == "chimera":
m = G.graph['rows']
n = G.graph['columns']
t = G.graph['tile']
# get a node placement function
xy_coords = chimera_node_placer_2d(m, n, t, scale, center, dim)
if G.graph.get('labels') == 'coordinate':
pos = {v: xy_coords(*v) for v in G.nodes()}
elif G.graph.get('data'):
pos = {v: xy_coords(*dat['chimera_index']) for v, dat in G.nodes(data=True)}
else:
coord = chimera_coordinates(m, n, t)
pos = {v: xy_coords(*coord.tuple(v)) for v in G.nodes()}
else:
# best case scenario, each node in G has a chimera_index attribute. Otherwise
# we will try to determine it using the find_chimera_indices function.
if all('chimera_index' in dat for __, dat in G.nodes(data=True)):
chimera_indices = {v: dat['chimera_index'] for v, dat in G.nodes(data=True)}
else:
chimera_indices = find_chimera_indices(G)
# we could read these off of the name attribute for G, but we would want the values in
# the nodes to override the name in case of conflict.
m = max(idx[0] for idx in itervalues(chimera_indices)) + 1
n = max(idx[1] for idx in itervalues(chimera_indices)) + 1
t = max(idx[3] for idx in itervalues(chimera_indices)) + 1
xy_coords = chimera_node_placer_2d(m, n, t, scale, center, dim)
# compute our coordinates
pos = {v: xy_coords(i, j, u, k) for v, (i, j, u, k) in iteritems(chimera_indices)}
return pos |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def chimera_node_placer_2d(m, n, t, scale=1., center=None, dim=2):
"""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. """ |
import numpy as np
tile_center = t // 2
tile_length = t + 3 # 1 for middle of cross, 2 for spacing between tiles
# want the enter plot to fill in [0, 1] when scale=1
scale /= max(m, n) * tile_length - 3
grid_offsets = {}
if center is None:
center = np.zeros(dim)
else:
center = np.asarray(center)
paddims = dim - 2
if paddims < 0:
raise ValueError("layout must have at least two dimensions")
if len(center) != dim:
raise ValueError("length of center coordinates must match dimension of layout")
def _xy_coords(i, j, u, k):
# row, col, shore, shore index
# first get the coordinatiates within the tile
if k < tile_center:
p = k
else:
p = k + 1
if u:
xy = np.array([tile_center, -1 * p])
else:
xy = np.array([p, -1 * tile_center])
# next offset the corrdinates based on the which tile
if i > 0 or j > 0:
if (i, j) in grid_offsets:
xy += grid_offsets[(i, j)]
else:
off = np.array([j * tile_length, -1 * i * tile_length])
xy += off
grid_offsets[(i, j)] = off
# convention for Chimera-lattice pictures is to invert the y-axis
return np.hstack((xy * scale, np.zeros(paddims))) + center
return _xy_coords |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def draw_chimera_embedding(G, *args, **kwargs):
"""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 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 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. """ |
draw_embedding(G, chimera_layout(G), *args, **kwargs) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def find_chimera_indices(G):
"""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 is a 4-tuple of integer Chimera indices. Examples -------- """ |
# if the nodes are orderable, we want the lowest-order one.
try:
nlist = sorted(G.nodes)
except TypeError:
nlist = G.nodes()
n_nodes = len(nlist)
# create the object that will store the indices
chimera_indices = {}
# ok, let's first check for the simple cases
if n_nodes == 0:
return chimera_indices
elif n_nodes == 1:
raise DWaveNetworkXException(
'Singleton graphs are not Chimera-structured')
elif n_nodes == 2:
return {nlist[0]: (0, 0, 0, 0), nlist[1]: (0, 0, 1, 0)}
# next, let's get the bicoloring of the graph; this raises an exception if the graph is
# not bipartite
coloring = color(G)
# we want the color of the node to be the u term in the Chimera-index, so we want the
# first node in nlist to be color 0
if coloring[nlist[0]] == 1:
coloring = {v: 1 - coloring[v] for v in coloring}
# we also want the diameter of the graph
# claim: diameter(G) == m + n for |G| > 2
dia = diameter(G)
# we have already handled the |G| <= 2 case, so we know, for diameter == 2, that the Chimera
# graph is a single tile
if dia == 2:
shore_indices = [0, 0]
for v in nlist:
u = coloring[v]
chimera_indices[v] = (0, 0, u, shore_indices[u])
shore_indices[u] += 1
return chimera_indices
# NB: max degree == shore size <==> one tile
raise Exception('not yet implemented for Chimera graphs with more than one tile') |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def chimera_elimination_order(m, n=None, t=None):
"""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 -------- """ |
if n is None:
n = m
if t is None:
t = 4
index_flip = m > n
if index_flip:
m, n = n, m
def chimeraI(m0, n0, k0, l0):
if index_flip:
return m*2*t*n0 + 2*t*m0 + t*(1-k0) + l0
else:
return n*2*t*m0 + 2*t*n0 + t*k0 + l0
order = []
for n_i in range(n):
for t_i in range(t):
for m_i in range(m):
order.append(chimeraI(m_i, n_i, 0, t_i))
for n_i in range(n):
for m_i in range(m):
for t_i in range(t):
order.append(chimeraI(m_i, n_i, 1, t_i))
return order |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def tuple(self, r):
""" 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 """ |
m, n, t = self.args
r, k = divmod(r, t)
r, u = divmod(r, 2)
i, j = divmod(r, n)
return i, j, u, k |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def ints(self, qlist):
""" 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 """ |
m, n, t = self.args
return (((n*i + j)*2 + u)*t + k for (i, j, u, k) in qlist) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def tuples(self, rlist):
""" 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 """ |
m, n, t = self.args
for r in rlist:
r, k = divmod(r, t)
r, u = divmod(r, 2)
i, j = divmod(r, n)
yield i, j, u, k |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def structural_imbalance(S, sampler=None, **sampler_args):
"""Returns an approximate set of frustrated edges and a bicoloring. A signed social network graph is a graph whose signed edges represent friendly/hostile interactions between nodes. A signed social network is considered balanced if it can be cleanly divided into two factions, where all relations within a faction are friendly, and all relations between factions are hostile. The measure of imbalance or frustration is the minimum number of edges that violate this rule. Parameters S : NetworkX graph A social graph on which each edge has a 'sign' attribute with a numeric value. sampler A binary quadratic model sampler. A sampler is a process that samples from low energy states in models defined by an Ising equation or a Quadratic Unconstrainted Binary Optimization Problem (QUBO). A sampler is expected to have a 'sample_qubo' and 'sample_ising' method. A sampler is expected to return an iterable of samples, in order of increasing energy. If no sampler is provided, one must be provided using the `set_default_sampler` function. sampler_args Additional keyword parameters are passed to the sampler. Returns ------- frustrated_edges : dict A dictionary of the edges that violate the edge sign. The imbalance of the network is the length of frustrated_edges. colors: dict A bicoloring of the nodes into two factions. Raises ------ ValueError If any edge does not have a 'sign' attribute. Examples -------- {} {'Alice': 0, 'Bob': 0, 'Eve': 1} {('Ted', 'Eve'):
{'sign': 1}} {'Bob': 1, 'Ted': 1, 'Alice': 1, 'Eve': 0} Notes ----- Samplers by their nature may not return the optimal solution. This function does not attempt to confirm the quality of the returned sample. References `Ising model on Wikipedia <https://en.wikipedia.org/wiki/Ising_model>`_ .. [FIA] Facchetti, G., Iacono G., and Altafini C. (2011). Computing global structural balance in large-scale signed social networks. PNAS, 108, no. 52, 20953-20958 """ |
h, J = structural_imbalance_ising(S)
# use the sampler to find low energy states
response = sampler.sample_ising(h, J, **sampler_args)
# we want the lowest energy sample
sample = next(iter(response))
# spins determine the color
colors = {v: (spin + 1) // 2 for v, spin in iteritems(sample)}
# frustrated edges are the ones that are violated
frustrated_edges = {}
for u, v, data in S.edges(data=True):
sign = data['sign']
if sign > 0 and colors[u] != colors[v]:
frustrated_edges[(u, v)] = data
elif sign < 0 and colors[u] == colors[v]:
frustrated_edges[(u, v)] = data
# else: not frustrated or sign == 0, no relation to violate
return frustrated_edges, colors |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def structural_imbalance_ising(S):
"""Construct the Ising problem to calculate the structural imbalance of a signed social network. A signed social network graph is a graph whose signed edges represent friendly/hostile interactions between nodes. A signed social network is considered balanced if it can be cleanly divided into two factions, where all relations within a faction are friendly, and all relations between factions are hostile. The measure of imbalance or frustration is the minimum number of edges that violate this rule. Parameters S : NetworkX graph A social graph on which each edge has a 'sign' attribute with a numeric value. Returns ------- h : dict The linear biases of the Ising problem. Each variable in the Ising problem represent a node in the signed social network. The solution that minimized the Ising problem will assign each variable a value, either -1 or 1. This bi-coloring defines the factions. J : dict The quadratic biases of the Ising problem. Raises ------ ValueError If any edge does not have a 'sign' attribute. Examples -------- {'Alice': 0.0, 'Bob': 0.0, 'Eve': 0.0} {('Alice', 'Bob'):
-1.0, ('Alice', 'Eve'):
1.0, ('Bob', 'Eve'):
1.0} """ |
h = {v: 0.0 for v in S}
J = {}
for u, v, data in S.edges(data=True):
try:
J[(u, v)] = -1. * data['sign']
except KeyError:
raise ValueError(("graph should be a signed social graph,"
"each edge should have a 'sign' attr"))
return h, J |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def is_simplicial(G, n):
"""Determines whether a node n in G is simplicial. Parameters G : NetworkX graph The graph on which to check whether node n is simplicial. n : node A node in graph G. Returns ------- is_simplicial : bool True if its neighbors form a clique. Examples -------- This example checks whether node 0 is simplicial for two graphs: G, a single Chimera unit cell, which is bipartite, and K_5, the :math:`K_5` complete graph. False True """ |
return all(u in G[v] for u, v in itertools.combinations(G[n], 2)) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def is_almost_simplicial(G, n):
"""Determines whether a node n in G is almost simplicial. Parameters G : NetworkX graph The graph on which to check whether node n is almost simplicial. n : node A node in graph G. Returns ------- is_almost_simplicial : bool True if all but one of its neighbors induce a clique Examples -------- This example checks whether node 0 is simplicial or almost simplicial for a :math:`K_5` complete graph with one edge removed. False True """ |
for w in G[n]:
if all(u in G[v] for u, v in itertools.combinations(G[n], 2) if u != w and v != w):
return True
return False |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def minor_min_width(G):
"""Computes a lower bound for the treewidth of graph G. Parameters G : NetworkX graph The graph on which to compute a lower bound on the treewidth. Returns ------- lb : int A lower bound on the treewidth. Examples -------- This example computes a lower bound for the treewidth of the :math:`K_7` complete graph. 6 References Based on the algorithm presented in [GD]_ """ |
# we need only deal with the adjacency structure of G. We will also
# be manipulating it directly so let's go ahead and make a new one
adj = {v: set(G[v]) for v in G}
lb = 0 # lower bound on treewidth
while len(adj) > 1:
# get the node with the smallest degree
v = min(adj, key=lambda v: len(adj[v]))
# find the vertex u such that the degree of u is minimal in the neighborhood of v
neighbors = adj[v]
if not neighbors:
# if v is a singleton, then we can just delete it
del adj[v]
continue
def neighborhood_degree(u):
Gu = adj[u]
return sum(w in Gu for w in neighbors)
u = min(neighbors, key=neighborhood_degree)
# update the lower bound
new_lb = len(adj[v])
if new_lb > lb:
lb = new_lb
# contract the edge between u, v
adj[v] = adj[v].union(n for n in adj[u] if n != v)
for n in adj[v]:
adj[n].add(v)
for n in adj[u]:
adj[n].discard(u)
del adj[u]
return lb |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def min_fill_heuristic(G):
"""Computes an upper bound on the treewidth of graph G based on the min-fill heuristic for the elimination ordering. Parameters G : NetworkX graph The graph on which to compute an upper bound for the treewidth. Returns ------- treewidth_upper_bound : int An upper bound on the treewidth of the graph G. order : list An elimination order that induces the treewidth. Examples -------- This example computes an upper bound for the treewidth of the :math:`K_4` complete graph. References Based on the algorithm presented in [GD]_ """ |
# we need only deal with the adjacency structure of G. We will also
# be manipulating it directly so let's go ahead and make a new one
adj = {v: set(G[v]) for v in G}
num_nodes = len(adj)
# preallocate the return values
order = [0] * num_nodes
upper_bound = 0
for i in range(num_nodes):
# get the node that adds the fewest number of edges when eliminated from the graph
v = min(adj, key=lambda x: _min_fill_needed_edges(adj, x))
# if the number of neighbours of v is higher than upper_bound, update
dv = len(adj[v])
if dv > upper_bound:
upper_bound = dv
# make v simplicial by making its neighborhood a clique then remove the
# node
_elim_adj(adj, v)
order[i] = v
return upper_bound, order |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def min_width_heuristic(G):
"""Computes an upper bound on the treewidth of graph G based on the min-width heuristic for the elimination ordering. Parameters G : NetworkX graph The graph on which to compute an upper bound for the treewidth. Returns ------- treewidth_upper_bound : int An upper bound on the treewidth of the graph G. order : list An elimination order that induces the treewidth. Examples -------- This example computes an upper bound for the treewidth of the :math:`K_4` complete graph. References Based on the algorithm presented in [GD]_ """ |
# we need only deal with the adjacency structure of G. We will also
# be manipulating it directly so let's go ahead and make a new one
adj = {v: set(G[v]) for v in G}
num_nodes = len(adj)
# preallocate the return values
order = [0] * num_nodes
upper_bound = 0
for i in range(num_nodes):
# get the node with the smallest degree. We add random() which picks a value
# in the range [0., 1.). This is ok because the lens are all integers. By
# adding a small random value, we randomize which node is chosen without affecting
# correctness.
v = min(adj, key=lambda u: len(adj[u]) + random())
# if the number of neighbours of v is higher than upper_bound, update
dv = len(adj[v])
if dv > upper_bound:
upper_bound = dv
# make v simplicial by making its neighborhood a clique then remove the
# node
_elim_adj(adj, v)
order[i] = v
return upper_bound, order |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def max_cardinality_heuristic(G):
"""Computes an upper bound on the treewidth of graph G based on the max-cardinality heuristic for the elimination ordering. Parameters G : NetworkX graph The graph on which to compute an upper bound for the treewidth. inplace : bool If True, G will be made an empty graph in the process of running the function, otherwise the function uses a copy of G. Returns ------- treewidth_upper_bound : int An upper bound on the treewidth of the graph G. order : list An elimination order that induces the treewidth. Examples -------- This example computes an upper bound for the treewidth of the :math:`K_4` complete graph. (3, [3, 1, 0, 2]) References Based on the algorithm presented in [GD]_ """ |
# we need only deal with the adjacency structure of G. We will also
# be manipulating it directly so let's go ahead and make a new one
adj = {v: set(G[v]) for v in G}
num_nodes = len(adj)
# preallocate the return values
order = [0] * num_nodes
upper_bound = 0
# we will need to track the nodes and how many labelled neighbors
# each node has
labelled_neighbors = {v: 0 for v in adj}
# working backwards
for i in range(num_nodes):
# pick the node with the most labelled neighbors
v = max(labelled_neighbors, key=lambda u: labelled_neighbors[u] + random())
del labelled_neighbors[v]
# increment all of its neighbors
for u in adj[v]:
if u in labelled_neighbors:
labelled_neighbors[u] += 1
order[-(i + 1)] = v
for v in order:
# if the number of neighbours of v is higher than upper_bound, update
dv = len(adj[v])
if dv > upper_bound:
upper_bound = dv
# make v simplicial by making its neighborhood a clique then remove the node
# add v to order
_elim_adj(adj, v)
return upper_bound, order |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _elim_adj(adj, n):
"""eliminates a variable, acting on the adj matrix of G, returning set of edges that were added. Parameters adj: dict vertices in a graph and neighbors is a set. Returns new_edges: set of edges that were added by eliminating v. """ |
neighbors = adj[n]
new_edges = set()
for u, v in itertools.combinations(neighbors, 2):
if v not in adj[u]:
adj[u].add(v)
adj[v].add(u)
new_edges.add((u, v))
new_edges.add((v, u))
for v in neighbors:
adj[v].discard(n)
del adj[n]
return new_edges |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def elimination_order_width(G, order):
"""Calculates the width of the tree decomposition induced by a variable elimination order. Parameters G : NetworkX graph The graph on which to compute the width of the tree decomposition. order : list The elimination order. Must be a list of all of the variables in G. Returns ------- treewidth : int The width of the tree decomposition induced by order. Examples -------- This example computes the width of the tree decomposition for the :math:`K_4` complete graph induced by an elimination order found through the min-width heuristic. (3, [1, 2, 0, 3]) 3 """ |
# we need only deal with the adjacency structure of G. We will also
# be manipulating it directly so let's go ahead and make a new one
adj = {v: set(G[v]) for v in G}
treewidth = 0
for v in order:
# get the degree of the eliminated variable
try:
dv = len(adj[v])
except KeyError:
raise ValueError('{} is in order but not in G'.format(v))
# the treewidth is the max of the current treewidth and the degree
if dv > treewidth:
treewidth = dv
# eliminate v by making it simplicial (acts on adj in place)
_elim_adj(adj, v)
# if adj is not empty, then order did not include all of the nodes in G.
if adj:
raise ValueError('not all nodes in G were in order')
return treewidth |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def treewidth_branch_and_bound(G, elimination_order=None, treewidth_upperbound=None):
"""Computes the treewidth of graph G and a corresponding perfect elimination ordering. Parameters G : NetworkX graph The graph on which to compute the treewidth and perfect elimination ordering. elimination_order: list (optional, Default None) An elimination order used as an initial best-known order. If a good order is provided, it may speed up computation. If not provided, the initial order is generated using the min-fill heuristic. treewidth_upperbound : int (optional, Default None) An upper bound on the treewidth. Note that using this parameter can result in no returned order. Returns ------- treewidth : int The treewidth of graph G. order : list An elimination order that induces the treewidth. Examples -------- This example computes the treewidth for the :math:`K_7` complete graph using an optionally provided elimination order (a sequential ordering of the nodes, arbitrally chosen). (6, [0, 1, 2, 3, 4, 5, 6]) References .. [GD] Gogate & Dechter, "A Complete Anytime Algorithm for Treewidth", https://arxiv.org/abs/1207.4109 """ |
# empty graphs have treewidth 0 and the nodes can be eliminated in
# any order
if not any(G[v] for v in G):
return 0, list(G)
# variable names are chosen to match the paper
# our order will be stored in vector x, named to be consistent with
# the paper
x = [] # the partial order
f = minor_min_width(G) # our current lower bound guess, f(s) in the paper
g = 0 # g(s) in the paper
# we need the best current update we can find.
ub, order = min_fill_heuristic(G)
# if the user has provided an upperbound or an elimination order, check those against
# our current best guess
if elimination_order is not None:
upperbound = elimination_order_width(G, elimination_order)
if upperbound <= ub:
ub, order = upperbound, elimination_order
if treewidth_upperbound is not None and treewidth_upperbound < ub:
# in this case the order might never be found
ub, order = treewidth_upperbound, []
# best found encodes the ub and the order
best_found = ub, order
# if our upper bound is the same as f, then we are done! Otherwise begin the
# algorithm
assert f <= ub, "Logic error"
if f < ub:
# we need only deal with the adjacency structure of G. We will also
# be manipulating it directly so let's go ahead and make a new one
adj = {v: set(G[v]) for v in G}
best_found = _branch_and_bound(adj, x, g, f, best_found)
return best_found |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _graph_reduction(adj, x, g, f):
"""we can go ahead and remove any simplicial or almost-simplicial vertices from adj. """ |
as_list = set()
as_nodes = {v for v in adj if len(adj[v]) <= f and is_almost_simplicial(adj, v)}
while as_nodes:
as_list.union(as_nodes)
for n in as_nodes:
# update g and f
dv = len(adj[n])
if dv > g:
g = dv
if g > f:
f = g
# eliminate v
x.append(n)
_elim_adj(adj, n)
# see if we have any more simplicial nodes
as_nodes = {v for v in adj if len(adj[v]) <= f and is_almost_simplicial(adj, v)}
return g, f, as_list |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _theorem5p4(adj, ub):
"""By Theorem 5.4, if any two vertices have ub + 1 common neighbors then we can add an edge between them. """ |
new_edges = set()
for u, v in itertools.combinations(adj, 2):
if u in adj[v]:
# already an edge
continue
if len(adj[u].intersection(adj[v])) > ub:
new_edges.add((u, v))
while new_edges:
for u, v in new_edges:
adj[u].add(v)
adj[v].add(u)
new_edges = set()
for u, v in itertools.combinations(adj, 2):
if u in adj[v]:
continue
if len(adj[u].intersection(adj[v])) > ub:
new_edges.add((u, v)) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _theorem6p1():
"""See Theorem 6.1 in paper.""" |
pruning_set = set()
def _prune(x):
if len(x) <= 2:
return False
# this is faster than tuple(x[-3:])
key = (tuple(x[:-2]), x[-2], x[-1])
return key in pruning_set
def _explored(x):
if len(x) >= 3:
prunable = (tuple(x[:-2]), x[-1], x[-2])
pruning_set.add(prunable)
return _prune, _explored |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def draw_qubit_graph(G, layout, linear_biases={}, quadratic_biases={}, nodelist=None, edgelist=None, cmap=None, edge_cmap=None, vmin=None, vmax=None, edge_vmin=None, edge_vmax=None, **kwargs):
"""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 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 quadratic_biases : dict (optional, default {}) A dict of biases associated with each edge in G. Should be of 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. """ |
if linear_biases or quadratic_biases:
# if linear biases and/or quadratic biases are provided, then color accordingly.
try:
import matplotlib.pyplot as plt
import matplotlib as mpl
except ImportError:
raise ImportError("Matplotlib and numpy required for draw_qubit_graph()")
if nodelist is None:
nodelist = G.nodes()
if edgelist is None:
edgelist = G.edges()
if cmap is None:
cmap = plt.get_cmap('coolwarm')
if edge_cmap is None:
edge_cmap = plt.get_cmap('coolwarm')
# any edges or nodes with an unspecified bias default to 0
def edge_color(u, v):
c = 0.
if (u, v) in quadratic_biases:
c += quadratic_biases[(u, v)]
if (v, u) in quadratic_biases:
c += quadratic_biases[(v, u)]
return c
def node_color(v):
c = 0.
if v in linear_biases:
c += linear_biases[v]
if (v, v) in quadratic_biases:
c += quadratic_biases[(v, v)]
return c
node_color = [node_color(v) for v in nodelist]
edge_color = [edge_color(u, v) for u, v in edgelist]
kwargs['edge_color'] = edge_color
kwargs['node_color'] = node_color
# the range of the color map is shared for nodes/edges and is symmetric
# around 0.
vmag = max(max(abs(c) for c in node_color), max(abs(c) for c in edge_color))
if vmin is None:
vmin = -1 * vmag
if vmax is None:
vmax = vmag
if edge_vmin is None:
edge_vmin = -1 * vmag
if edge_vmax is None:
edge_vmax = vmag
draw(G, layout, nodelist=nodelist, edgelist=edgelist,
cmap=cmap, edge_cmap=edge_cmap, vmin=vmin, vmax=vmax, edge_vmin=edge_vmin,
edge_vmax=edge_vmax,
**kwargs)
# if the biases are provided, then add a legend explaining the color map
if linear_biases or quadratic_biases:
fig = plt.figure(1)
# cax = fig.add_axes([])
cax = fig.add_axes([.9, 0.2, 0.04, 0.6]) # left, bottom, width, height
mpl.colorbar.ColorbarBase(cax, cmap=cmap,
norm=mpl.colors.Normalize(vmin=-1 * vmag, vmax=vmag, clip=False),
orientation='vertical') |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def min_vertex_coloring(G, sampler=None, **sampler_args):
"""Returns an approximate minimum vertex coloring. Vertex coloring is the problem of assigning a color to the vertices of a graph in a way that no adjacent vertices have the same color. A minimum vertex coloring is the problem of solving the vertex coloring problem using the smallest number of colors. Since neighboring vertices must satisfy a constraint of having different colors, the problem can be posed as a binary constraint satisfaction problem. Defines a QUBO with ground states corresponding to minimum vertex colorings and uses the sampler to sample from it. Parameters G : NetworkX graph The graph on which to find a minimum vertex coloring. sampler A binary quadratic model sampler. A sampler is a process that samples from low energy states in models defined by an Ising equation or a Quadratic Unconstrained Binary Optimization Problem (QUBO). A sampler is expected to have a 'sample_qubo' and 'sample_ising' method. A sampler is expected to return an iterable of samples, in order of increasing energy. If no sampler is provided, one must be provided using the `set_default_sampler` function. sampler_args Additional keyword parameters are passed to the sampler. Returns ------- coloring : dict A coloring for each vertex in G such that no adjacent nodes Example ------- This example colors a single Chimera unit cell. It colors the four horizontal qubits one color (0) and the four vertical qubits another (1). {0: 0, 1: 0, 2: 0, 3: 0, 4: 1, 5: 1, 6: 1, 7: 1} References .. [DWMP] Dahl, E., "Programming the D-Wave: Map Coloring Problem", https://www.dwavesys.com/sites/default/files/Map%20Coloring%20WP2.pdf Notes ----- Samplers by their nature may not return the optimal solution. This function does not attempt to confirm the quality of the returned sample. """ |
# if the given graph is not connected, apply the function to each connected component
# seperately.
if not nx.is_connected(G):
coloring = {}
for subG in (G.subgraph(c).copy() for c in nx.connected_components(G)):
sub_coloring = min_vertex_coloring(subG, sampler, **sampler_args)
coloring.update(sub_coloring)
return coloring
n_nodes = len(G) # number of nodes
n_edges = len(G.edges) # number of edges
# ok, first up, we can eliminate a few graph types trivially
# Graphs with no edges, have chromatic number 1
if not n_edges:
return {node: 0 for node in G}
# Complete graphs have chromatic number N
if n_edges == n_nodes * (n_nodes - 1) // 2:
return {node: color for color, node in enumerate(G)}
# The number of variables in the QUBO is approximately the number of nodes in the graph
# times the number of potential colors, so we want as tight an upper bound on the
# chromatic number (chi) as possible
chi_ub = _chromatic_number_upper_bound(G, n_nodes, n_edges)
# now we can start coloring. Without loss of generality, we can determine some of
# the node colors before trying to solve.
partial_coloring, possible_colors, chi_lb = _partial_precolor(G, chi_ub)
# ok, to get the rest of the coloring, we need to start building the QUBO. We do this
# by assigning a variable x_v_c for each node v and color c. This variable will be 1
# when node v is colored c, and 0 otherwise.
# let's assign an index to each of the variables
counter = itertools.count()
x_vars = {v: {c: next(counter) for c in possible_colors[v]} for v in possible_colors}
# now we have three different constraints we wish to add.
# the first constraint enforces the coloring rule, that for each pair of vertices
# u, v that share an edge, they should be different colors
Q_neighbor = _vertex_different_colors_qubo(G, x_vars)
# the second constraint enforces that each vertex has a single color assigned
Q_vertex = _vertex_one_color_qubo(x_vars)
# the third constraint is that we want a minimum vertex coloring, so we want to
# disincentivize the colors we might not need.
Q_min_color = _minimum_coloring_qubo(x_vars, chi_lb, chi_ub, magnitude=.75)
# combine all three constraints
Q = Q_neighbor
for (u, v), bias in iteritems(Q_vertex):
if (u, v) in Q:
Q[(u, v)] += bias
elif (v, u) in Q:
Q[(v, u)] += bias
else:
Q[(u, v)] = bias
for (v, v), bias in iteritems(Q_min_color):
if (v, v) in Q:
Q[(v, v)] += bias
else:
Q[(v, v)] = bias
# use the sampler to find low energy states
response = sampler.sample_qubo(Q, **sampler_args)
# we want the lowest energy sample
sample = next(iter(response))
# read off the coloring
for v in x_vars:
for c in x_vars[v]:
if sample[x_vars[v][c]]:
partial_coloring[v] = c
return partial_coloring |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _minimum_coloring_qubo(x_vars, chi_lb, chi_ub, magnitude=1.):
"""We want to disincentivize unneeded colors. Generates the QUBO that does that. """ |
# if we already know the chromatic number, then we don't need to
# disincentivize any colors.
if chi_lb == chi_ub:
return {}
# we might need to use some of the colors, so we want to disincentivize
# them in increasing amounts, linearly.
scaling = magnitude / (chi_ub - chi_lb)
# build the QUBO
Q = {}
for v in x_vars:
for f, color in enumerate(range(chi_lb, chi_ub)):
idx = x_vars[v][color]
Q[(idx, idx)] = (f + 1) * scaling
return Q |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _vertex_different_colors_qubo(G, x_vars):
"""For each vertex, it should not have the same color as any of its neighbors. Generates the QUBO to enforce this constraint. Notes ----- Does not enforce each node having a single color. Ground energy is 0, infeasible gap is 1. """ |
Q = {}
for u, v in G.edges:
if u not in x_vars or v not in x_vars:
continue
for color in x_vars[u]:
if color in x_vars[v]:
Q[(x_vars[u][color], x_vars[v][color])] = 1.
return Q |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _vertex_one_color_qubo(x_vars):
"""For each vertex, it should have exactly one color. Generates the QUBO to enforce this constraint. Notes ----- Does not enforce neighboring vertices having different colors. Ground energy is -1 * |G|, infeasible gap is 1. """ |
Q = {}
for v in x_vars:
for color in x_vars[v]:
idx = x_vars[v][color]
Q[(idx, idx)] = -1
for color0, color1 in itertools.combinations(x_vars[v], 2):
idx0 = x_vars[v][color0]
idx1 = x_vars[v][color1]
Q[(idx0, idx1)] = 2
return Q |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _partial_precolor(G, chi_ub):
"""In order to reduce the number of variables in the QUBO, we want to color as many nodes as possible without affecting the min vertex coloring. Without loss of generality, we can choose a single maximal clique and color each node in it uniquely. Returns ------- partial_coloring : dict A dict describing a partial coloring of the nodes of G. Of the form possible_colors : dict A dict giving the possible colors for each node in G not already chi_lb : int A lower bound on the chromatic number chi. Notes ----- partial_coloring.keys() and possible_colors.keys() should be disjoint. """ |
# find a random maximal clique and give each node in it a unique color
v = next(iter(G))
clique = [v]
for u in G[v]:
if all(w in G[u] for w in clique):
clique.append(u)
partial_coloring = {v: c for c, v in enumerate(clique)}
chi_lb = len(partial_coloring) # lower bound for the chromatic number
# now for each uncolored node determine the possible colors
possible_colors = {v: set(range(chi_ub)) for v in G if v not in partial_coloring}
for v, color in iteritems(partial_coloring):
for u in G[v]:
if u in possible_colors:
possible_colors[u].discard(color)
# TODO: there is more here that can be done. For instance some nodes now
# might only have one possible color. Or there might only be one node
# remaining to color
return partial_coloring, possible_colors, chi_lb |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def is_cycle(G):
"""Determines whether the given graph is a cycle or circle graph. A cycle graph or circular graph is a graph that consists of a single cycle. https://en.wikipedia.org/wiki/Cycle_graph Parameters G : NetworkX graph Returns ------- is_cycle : bool True if the graph consists of a single cycle. """ |
trailing, leading = next(iter(G.edges))
start_node = trailing
# travel around the graph, checking that each node has degree exactly two
# also track how many nodes were visited
n_visited = 1
while leading != start_node:
neighbors = G[leading]
if len(neighbors) != 2:
return False
node1, node2 = neighbors
if node1 == trailing:
trailing, leading = leading, node2
else:
trailing, leading = leading, node1
n_visited += 1
# if we haven't visited all of the nodes, then it is not a connected cycle
return n_visited == len(G) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def is_vertex_coloring(G, coloring):
"""Determines whether the given coloring is a vertex coloring of graph G. Parameters G : NetworkX graph The graph on which the vertex coloring is applied. coloring : dict A coloring of the nodes of G. Should be a dict of the form Returns ------- is_vertex_coloring : bool True if the given coloring defines a vertex coloring; that is, no two adjacent vertices share a color. Example ------- This example colors checks two colorings for a graph, G, of a single Chimera unit cell. The first uses one color (0) for the four horizontal qubits and another (1) for the four vertical qubits, in which case there are no adjacencies; the second coloring swaps the color of one node. True False """ |
return all(coloring[u] != coloring[v] for u, v in G.edges) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def maximal_matching(G, sampler=None, **sampler_args):
"""Finds an approximate maximal matching. Defines a QUBO with ground states corresponding to a maximal matching and uses the sampler to sample from it. A matching is a subset of edges in which no node occurs more than once. A maximal matching is one in which no edges from G can be added without violating the matching rule. Parameters G : NetworkX graph The graph on which to find a maximal matching. sampler A binary quadratic model sampler. A sampler is a process that samples from low energy states in models defined by an Ising equation or a Quadratic Unconstrained Binary Optimization Problem (QUBO). A sampler is expected to have a 'sample_qubo' and 'sample_ising' method. A sampler is expected to return an iterable of samples, in order of increasing energy. If no sampler is provided, one must be provided using the `set_default_sampler` function. sampler_args Additional keyword parameters are passed to the sampler. Returns ------- matching : set A maximal matching of the graph. Notes ----- Samplers by their nature may not return the optimal solution. This function does not attempt to confirm the quality of the returned sample. References `Matching on Wikipedia <https://en.wikipedia.org/wiki/Matching_(graph_theory)>`_ `QUBO on Wikipedia <https://en.wikipedia.org/wiki/Quadratic_unconstrained_binary_optimization>`_ Based on the formulation presented in [AL]_ """ |
# the maximum degree
delta = max(G.degree(node) for node in G)
# use the maximum degree to determine the infeasible gaps
A = 1.
if delta == 2:
B = .75
else:
B = .75 * A / (delta - 2.) # we want A > (delta - 2) * B
# each edge in G gets a variable, so let's create those
edge_mapping = _edge_mapping(G)
# build the QUBO
Q = _maximal_matching_qubo(G, edge_mapping, magnitude=B)
Qm = _matching_qubo(G, edge_mapping, magnitude=A)
for edge, bias in Qm.items():
if edge not in Q:
Q[edge] = bias
else:
Q[edge] += bias
# use the sampler to find low energy states
response = sampler.sample_qubo(Q, **sampler_args)
# we want the lowest energy sample
sample = next(iter(response))
# the matching are the edges that are 1 in the sample
return set(edge for edge in G.edges if sample[edge_mapping[edge]] > 0) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def is_maximal_matching(G, matching):
"""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. True False True """ |
touched_nodes = set().union(*matching)
# first check if a matching
if len(touched_nodes) != len(matching) * 2:
return False
# now for each edge, check that at least one of its variables is
# already in the matching
for (u, v) in G.edges:
if u not in touched_nodes and v not in touched_nodes:
return False
return True |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _maximal_matching_qubo(G, edge_mapping, magnitude=1.):
"""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 """ |
Q = {}
# for each node n in G, define a variable y_n to be 1 when n has a colored edge
# and 0 otherwise.
# for each edge (u, v) in the graph we want to enforce y_u OR y_v. This is because
# if both y_u == 0 and y_v == 0, then we could add (u, v) to the matching.
for (u, v) in G.edges:
# 1 - y_v - y_u + y_v*y_u
# for each edge connected to u
for edge in G.edges(u):
x = edge_mapping[edge]
if (x, x) not in Q:
Q[(x, x)] = -1 * magnitude
else:
Q[(x, x)] -= magnitude
# for each edge connected to v
for edge in G.edges(v):
x = edge_mapping[edge]
if (x, x) not in Q:
Q[(x, x)] = -1 * magnitude
else:
Q[(x, x)] -= magnitude
for e0 in G.edges(v):
x0 = edge_mapping[e0]
for e1 in G.edges(u):
x1 = edge_mapping[e1]
if x0 < x1:
if (x0, x1) not in Q:
Q[(x0, x1)] = magnitude
else:
Q[(x0, x1)] += magnitude
else:
if (x1, x0) not in Q:
Q[(x1, x0)] = magnitude
else:
Q[(x1, x0)] += magnitude
return Q |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _matching_qubo(G, edge_mapping, magnitude=1.):
"""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 """ |
Q = {}
# We wish to enforce the behavior that no node has two colored edges
for node in G:
# for each pair of edges that contain node
for edge0, edge1 in itertools.combinations(G.edges(node), 2):
v0 = edge_mapping[edge0]
v1 = edge_mapping[edge1]
# penalize both being True
Q[(v0, v1)] = magnitude
return Q |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def canonical_chimera_labeling(G, t=None):
"""Returns a mapping from the labels of G to chimera-indexed labeling. Parameters G : NetworkX graph A Chimera-structured graph. t : int (optional, default 4) Size of the shore within each Chimera tile. Returns ------- chimera_indices: dict A mapping from the current labels to a 4-tuple of Chimera indices. """ |
adj = G.adj
if t is None:
if hasattr(G, 'edges'):
num_edges = len(G.edges)
else:
num_edges = len(G.quadratic)
t = _chimera_shore_size(adj, num_edges)
chimera_indices = {}
row = col = 0
root = min(adj, key=lambda v: len(adj[v]))
horiz, verti = rooted_tile(adj, root, t)
while len(chimera_indices) < len(adj):
new_indices = {}
if row == 0:
# if we're in the 0th row, we can assign the horizontal randomly
for si, v in enumerate(horiz):
new_indices[v] = (row, col, 0, si)
else:
# we need to match the row above
for v in horiz:
north = [u for u in adj[v] if u in chimera_indices]
assert len(north) == 1
i, j, u, si = chimera_indices[north[0]]
assert i == row - 1 and j == col and u == 0
new_indices[v] = (row, col, 0, si)
if col == 0:
# if we're in the 0th col, we can assign the vertical randomly
for si, v in enumerate(verti):
new_indices[v] = (row, col, 1, si)
else:
# we need to match the column to the east
for v in verti:
east = [u for u in adj[v] if u in chimera_indices]
assert len(east) == 1
i, j, u, si = chimera_indices[east[0]]
assert i == row and j == col - 1 and u == 1
new_indices[v] = (row, col, 1, si)
chimera_indices.update(new_indices)
# get the next root
root_neighbours = [v for v in adj[root] if v not in chimera_indices]
if len(root_neighbours) == 1:
# we can increment the row
root = root_neighbours[0]
horiz, verti = rooted_tile(adj, root, t)
row += 1
else:
# need to go back to row 0, and increment the column
assert not root_neighbours # should be empty
# we want (0, col, 1, 0), we could cache this, but for now let's just go look for it
# the slow way
vert_root = [v for v in chimera_indices if chimera_indices[v] == (0, col, 1, 0)][0]
vert_root_neighbours = [v for v in adj[vert_root] if v not in chimera_indices]
if vert_root_neighbours:
verti, horiz = rooted_tile(adj, vert_root_neighbours[0], t)
root = next(iter(horiz))
row = 0
col += 1
return chimera_indices |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def maximum_weighted_independent_set(G, weight=None, sampler=None, lagrange=2.0, **sampler_args):
"""Returns an approximate maximum weighted independent set. Defines a QUBO with ground states corresponding to a maximum weighted independent set and uses the sampler to sample from it. An independent set is a set of nodes such that the subgraph of G induced by these nodes contains no edges. A maximum independent set is an independent set of maximum total node weight. Parameters G : NetworkX graph The graph on which to find a maximum cut weighted independent set. weight : string, optional (default None) If None, every node has equal weight. If a string, use this node attribute as the node weight. A node without this attribute is assumed to have max weight. sampler A binary quadratic model sampler. A sampler is a process that samples from low energy states in models defined by an Ising equation or a Quadratic Unconstrained Binary Optimization Problem (QUBO). A sampler is expected to have a 'sample_qubo' and 'sample_ising' method. A sampler is expected to return an iterable of samples, in order of increasing energy. If no sampler is provided, one must be provided using the `set_default_sampler` function. lagrange : optional (default 2) Lagrange parameter to weight constraints (no edges within set) versus objective (largest set possible). sampler_args Additional keyword parameters are passed to the sampler. Returns ------- indep_nodes : list List of nodes that form a maximum weighted independent set, as determined by the given sampler. Notes ----- Samplers by their nature may not return the optimal solution. This function does not attempt to confirm the quality of the returned sample. References `Independent Set on Wikipedia <https://en.wikipedia.org/wiki/Independent_set_(graph_theory)>`_ `QUBO on Wikipedia <https://en.wikipedia.org/wiki/Quadratic_unconstrained_binary_optimization>`_ .. [AL] Lucas, A. (2014). Ising formulations of many NP problems. Frontiers in Physics, Volume 2, Article 5. """ |
# Get a QUBO representation of the problem
Q = maximum_weighted_independent_set_qubo(G, weight, lagrange)
# use the sampler to find low energy states
response = sampler.sample_qubo(Q, **sampler_args)
# we want the lowest energy sample
sample = next(iter(response))
# nodes that are spin up or true are exactly the ones in S.
return [node for node in sample if sample[node] > 0] |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def maximum_independent_set(G, sampler=None, lagrange=2.0, **sampler_args):
"""Returns an approximate maximum independent set. Defines a QUBO with ground states corresponding to a maximum independent set and uses the sampler to sample from it. An independent set is a set of nodes such that the subgraph of G induced by these nodes contains no edges. A maximum independent set is an independent set of largest possible size. Parameters G : NetworkX graph The graph on which to find a maximum cut independent set. sampler A binary quadratic model sampler. A sampler is a process that samples from low energy states in models defined by an Ising equation or a Quadratic Unconstrained Binary Optimization Problem (QUBO). A sampler is expected to have a 'sample_qubo' and 'sample_ising' method. A sampler is expected to return an iterable of samples, in order of increasing energy. If no sampler is provided, one must be provided using the `set_default_sampler` function. lagrange : optional (default 2) Lagrange parameter to weight constraints (no edges within set) versus objective (largest set possible). sampler_args Additional keyword parameters are passed to the sampler. Returns ------- indep_nodes : list List of nodes that form a maximum independent set, as determined by the given sampler. Example ------- This example uses a sampler from `dimod <https://github.com/dwavesystems/dimod>`_ to find a maximum independent set for a graph of a Chimera unit cell created using the `chimera_graph()` function. Notes ----- Samplers by their nature may not return the optimal solution. This function does not attempt to confirm the quality of the returned sample. References `Independent Set on Wikipedia <https://en.wikipedia.org/wiki/Independent_set_(graph_theory)>`_ `QUBO on Wikipedia <https://en.wikipedia.org/wiki/Quadratic_unconstrained_binary_optimization>`_ .. [AL] Lucas, A. (2014). Ising formulations of many NP problems. Frontiers in Physics, Volume 2, Article 5. """ |
return maximum_weighted_independent_set(G, None, sampler, lagrange, **sampler_args) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def maximum_weighted_independent_set_qubo(G, weight=None, lagrange=2.0):
"""Return the QUBO with ground states corresponding to a maximum weighted independent set. Parameters G : NetworkX graph weight : string, optional (default None) If None, every node has equal weight. If a string, use this node attribute as the node weight. A node without this attribute is assumed to have max weight. lagrange : optional (default 2) Lagrange parameter to weight constraints (no edges within set) versus objective (largest set possible). Returns ------- QUBO : dict The QUBO with ground states corresponding to a maximum weighted independent set. Examples -------- -1.0 -1.0 2.0 """ |
# empty QUBO for an empty graph
if not G:
return {}
# We assume that the sampler can handle an unstructured QUBO problem, so let's set one up.
# Let us define the largest independent set to be S.
# For each node n in the graph, we assign a boolean variable v_n, where v_n = 1 when n
# is in S and v_n = 0 otherwise.
# We call the matrix defining our QUBO problem Q.
# On the diagnonal, we assign the linear bias for each node to be the negative of its weight.
# This means that each node is biased towards being in S. Weights are scaled to a maximum of 1.
# Negative weights are considered 0.
# On the off diagnonal, we assign the off-diagonal terms of Q to be 2. Thus, if both
# nodes are in S, the overall energy is increased by 2.
cost = dict(G.nodes(data=weight, default=1))
scale = max(cost.values())
Q = {(node, node): min(-cost[node] / scale, 0.0) for node in G}
Q.update({edge: lagrange for edge in G.edges})
return Q |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def min_weighted_vertex_cover(G, weight=None, sampler=None, **sampler_args):
"""Returns an approximate minimum weighted vertex cover. Defines a QUBO with ground states corresponding to a minimum weighted vertex cover and uses the sampler to sample from it. A vertex cover is a set of vertices such that each edge of the graph is incident with at least one vertex in the set. A minimum weighted vertex cover is the vertex cover of minimum total node weight. Parameters G : NetworkX graph weight : string, optional (default None) If None, every node has equal weight. If a string, use this node attribute as the node weight. A node without this attribute is assumed to have max weight. sampler A binary quadratic model sampler. A sampler is a process that samples from low energy states in models defined by an Ising equation or a Quadratic Unconstrained Binary Optimization Problem (QUBO). A sampler is expected to have a 'sample_qubo' and 'sample_ising' method. A sampler is expected to return an iterable of samples, in order of increasing energy. If no sampler is provided, one must be provided using the `set_default_sampler` function. sampler_args Additional keyword parameters are passed to the sampler. Returns ------- vertex_cover : list List of nodes that the form a the minimum weighted vertex cover, as determined by the given sampler. Notes ----- Samplers by their nature may not return the optimal solution. This function does not attempt to confirm the quality of the returned sample. https://en.wikipedia.org/wiki/Vertex_cover https://en.wikipedia.org/wiki/Quadratic_unconstrained_binary_optimization References Based on the formulation presented in [AL]_ """ |
indep_nodes = set(maximum_weighted_independent_set(G, weight, sampler, **sampler_args))
return [v for v in G if v not in indep_nodes] |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def is_vertex_cover(G, vertex_cover):
"""Determines whether the given set of vertices is a vertex cover of graph G. A vertex cover is a set of vertices such that each edge of the graph is incident with at least one vertex in the set. Parameters G : NetworkX graph The graph on which to check the vertex cover. vertex_cover : Iterable of nodes. Returns ------- is_cover : bool True if the given iterable forms a vertex cover. Examples -------- This example checks two covers for a graph, G, of a single Chimera unit cell. The first uses the set of the four horizontal qubits, which do constitute a cover; the second set removes one node. True False """ |
cover = set(vertex_cover)
return all(u in cover or v in cover for u, v in G.edges) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def pegasus_layout(G, scale=1., center=None, dim=2, crosses=False):
"""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 -------- """ |
if not isinstance(G, nx.Graph) or G.graph.get("family") != "pegasus":
raise ValueError("G must be generated by dwave_networkx.pegasus_graph")
if G.graph.get('labels') == 'nice':
m = 3*(G.graph['rows']-1)
c_coords = chimera_node_placer_2d(m, m, 4, scale=scale, center=center, dim=dim)
def xy_coords(t, y, x, u, k): return c_coords(3*y+2-t, 3*x+t, u, k)
pos = {v: xy_coords(*v) for v in G.nodes()}
else:
xy_coords = pegasus_node_placer_2d(G, scale, center, dim, crosses=crosses)
if G.graph.get('labels') == 'coordinate':
pos = {v: xy_coords(*v) for v in G.nodes()}
elif G.graph.get('data'):
pos = {v: xy_coords(*dat['pegasus_index']) for v, dat in G.nodes(data=True)}
else:
m = G.graph.get('rows')
coord = pegasus_coordinates(m)
pos = {v: xy_coords(*coord.tuple(v)) for v in G.nodes()}
return pos |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def pegasus_node_placer_2d(G, scale=1., center=None, dim=2, crosses=False):
"""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. """ |
import numpy as np
m = G.graph.get('rows')
h_offsets = G.graph.get("horizontal_offsets")
v_offsets = G.graph.get("vertical_offsets")
tile_width = G.graph.get("tile")
tile_center = tile_width / 2 - .5
# want the enter plot to fill in [0, 1] when scale=1
scale /= m * tile_width
if center is None:
center = np.zeros(dim)
else:
center = np.asarray(center)
paddims = dim - 2
if paddims < 0:
raise ValueError("layout must have at least two dimensions")
if len(center) != dim:
raise ValueError("length of center coordinates must match dimension of layout")
if crosses:
# adjustment for crosses
cross_shift = 2.
else:
cross_shift = 0.
def _xy_coords(u, w, k, z):
# orientation, major perpendicular offset, minor perpendicular offset, parallel offset
if k % 2:
p = -.1
else:
p = .1
if u:
xy = np.array([z*tile_width+h_offsets[k] + tile_center, -tile_width*w-k-p+cross_shift])
else:
xy = np.array([tile_width*w+k+p+cross_shift, -z*tile_width-v_offsets[k]-tile_center])
# convention for Pegasus-lattice pictures is to invert the y-axis
return np.hstack((xy * scale, np.zeros(paddims))) + center
return _xy_coords |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def draw_pegasus(G, crosses=False, **kwargs):
"""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 quadratic_biases : dict (optional, default {}) A dict of biases associated with each edge in G. Should be of 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 -------- """ |
draw_qubit_graph(G, pegasus_layout(G, crosses=crosses), **kwargs) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def draw_pegasus_embedding(G, *args, **kwargs):
"""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 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 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. """ |
crosses = kwargs.pop("crosses", False)
draw_embedding(G, pegasus_layout(G, crosses=crosses), *args, **kwargs) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def binary_quadratic_model_sampler(which_args):
"""Decorator to validate sampler arguments. Parameters which_args : int or sequence of ints Location of the sampler arguments of the input function in the form `function_name(args, *kw)`. If more than one sampler is allowed, can be a list of locations. Returns ------- _binary_quadratic_model_sampler : function Caller function that validates the sampler format. A sampler is expected to have `sample_qubo` and `sample_ising` methods. Alternatively, if no sampler is provided (or sampler is None), the sampler set by the `set_default_sampler` function is provided to the function. Examples -------- Decorate functions like this:: @binary_quadratic_model_sampler(1) def maximal_matching(G, sampler, **sampler_args):
pass This example validates two placeholder samplers, which return a correct response only in the case of finding an independent set on a complete graph (where one node is always an independent set), the first valid, the second missing a method. [0] TypeError Traceback (most recent call last) <ipython-input-35-670b71b268c7> in <module>() ----> 1 independent_set(G, IllDefinedSampler) <decorator-gen-628> in independent_set(G, sampler, **sampler_args) /usr/local/lib/python2.7/dist-packages/dwave_networkx/utils/decorators.pyc in _binary_quadratic_model_sampler(f, *args, **kw) 61 62 if not hasattr(sampler, "sample_qubo") or not callable(sampler.sample_qubo):
---> 63 raise TypeError("expected sampler to have a 'sample_qubo' method") 64 if not hasattr(sampler, "sample_ising") or not callable(sampler.sample_ising):
65 raise TypeError("expected sampler to have a 'sample_ising' method") TypeError: expected sampler to have a 'sample_qubo' method """ |
@decorator
def _binary_quadratic_model_sampler(f, *args, **kw):
# convert into a sequence if necessary
if isinstance(which_args, int):
iter_args = (which_args,)
else:
iter_args = iter(which_args)
# check each sampler for the correct methods
new_args = [arg for arg in args]
for idx in iter_args:
sampler = args[idx]
# if no sampler is provided, get the default sampler if it has
# been set
if sampler is None:
# this sampler has already been vetted
default_sampler = dnx.get_default_sampler()
if default_sampler is None:
raise dnx.DWaveNetworkXMissingSampler('no default sampler set')
new_args[idx] = default_sampler
continue
if not hasattr(sampler, "sample_qubo") or not callable(sampler.sample_qubo):
raise TypeError("expected sampler to have a 'sample_qubo' method")
if not hasattr(sampler, "sample_ising") or not callable(sampler.sample_ising):
raise TypeError("expected sampler to have a 'sample_ising' method")
# now run the function and return the results
return f(*new_args, **kw)
return _binary_quadratic_model_sampler |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def duration_to_number(duration, units='seconds'):
"""If duration is already a numeric type, then just return duration. If duration is a timedelta, return a duration in seconds. TODO: allow for multiple types of units. """ |
if isinstance(duration, (int, float, long)):
return duration
elif isinstance(duration, (datetime.timedelta,)):
if units == 'seconds':
return duration.total_seconds()
else:
msg = 'unit "%s" is not supported' % units
raise NotImplementedError(msg)
elif duration == inf or duration == -inf:
msg = "Can't convert infinite duration to number"
raise ValueError(msg)
else:
msg = 'duration is an unknown type (%s)' % duration
raise TypeError(msg) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def convert_args_to_list(args):
"""Convert all iterable pairs of inputs into a list of list""" |
list_of_pairs = []
if len(args) == 0:
return []
if any(isinstance(arg, (list, tuple)) for arg in args):
# Domain([[1, 4]])
# Domain([(1, 4)])
# Domain([(1, 4), (5, 8)])
# Domain([[1, 4], [5, 8]])
if len(args) == 1 and \
any(isinstance(arg, (list, tuple)) for arg in args[0]):
for item in args[0]:
list_of_pairs.append(list(item))
else:
# Domain([1, 4])
# Domain((1, 4))
# Domain((1, 4), (5, 8))
# Domain([1, 4], [5, 8])
for item in args:
list_of_pairs.append(list(item))
else:
# Domain(1, 2)
if len(args) == 2:
list_of_pairs.append(list(args))
else:
msg = "The argument type is invalid. ".format(args)
raise TypeError(msg)
return list_of_pairs |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def variance(self):
"""Variance of the distribution.""" |
_self = self._discard_value(None)
if not _self.total():
return 0.0
mean = _self.mean()
weighted_central_moment = sum(
count * (value - mean)**2 for value, count in iteritems(_self)
)
return weighted_central_moment / float(_self.total()) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def normalized(self):
"""Return a normalized version of the histogram where the values sum to one. """ |
total = self.total()
result = Histogram()
for value, count in iteritems(self):
try:
result[value] = count / float(total)
except UnorderableElements as e:
result = Histogram.from_dict(dict(result), key=hash)
result[value] = count / float(total)
return result |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _quantile_function(self, alpha=0.5, smallest_count=None):
"""Return a function that returns the quantile values for this histogram. """ |
total = float(self.total())
smallest_observed_count = min(itervalues(self))
if smallest_count is None:
smallest_count = smallest_observed_count
else:
smallest_count = min(smallest_count, smallest_observed_count)
beta = alpha * smallest_count
debug_plot = []
cumulative_sum = 0.0
inverse = sortedcontainers.SortedDict()
for value, count in iteritems(self):
debug_plot.append((cumulative_sum / total, value))
inverse[(cumulative_sum + beta) / total] = value
cumulative_sum += count
inverse[(cumulative_sum - beta) / total] = value
debug_plot.append((cumulative_sum / total, value))
# get maximum and minumum q values
q_min = inverse.iloc[0]
q_max = inverse.iloc[-1]
# this stuff if helpful for debugging -- keep it in here
# for i, j in debug_plot:
# print i, j
# print ''
# for i, j in inverse.iteritems():
# print i, j
# print ''
def function(q):
if q < 0.0 or q > 1.0:
msg = 'invalid quantile %s, need `0 <= q <= 1`' % q
raise ValueError(msg)
elif q < q_min:
q = q_min
elif q > q_max:
q = q_max
# if beta is
if beta > 0:
if q in inverse:
result = inverse[q]
else:
previous_index = inverse.bisect_left(q) - 1
x1 = inverse.iloc[previous_index]
x2 = inverse.iloc[previous_index + 1]
y1 = inverse[x1]
y2 = inverse[x2]
result = (y2 - y1) * (q - x1) / float(x2 - x1) + y1
else:
if q in inverse:
previous_index = inverse.bisect_left(q) - 1
x1 = inverse.iloc[previous_index]
x2 = inverse.iloc[previous_index + 1]
y1 = inverse[x1]
y2 = inverse[x2]
result = 0.5 * (y1 + y2)
else:
previous_index = inverse.bisect_left(q) - 1
x1 = inverse.iloc[previous_index]
result = inverse[x1]
return float(result)
return function |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def get(self, time, interpolate='previous'):
"""Get the value of the time series, even in-between measured values. """ |
try:
getter = self.getter_functions[interpolate]
except KeyError:
msg = (
"unknown value '{}' for interpolate, "
"valid values are in [{}]"
).format(interpolate, ', '.join(self.getter_functions))
raise ValueError(msg)
else:
return getter(time) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def set(self, time, value, compact=False):
"""Set the value for the time series. If compact is True, only set the value if it's different from what it would be anyway. """ |
if (len(self) == 0) or (not compact) or \
(compact and self.get(time) != value):
self._d[time] = value |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def set_interval(self, start, end, value, compact=False):
"""Set the value for the time series on an interval. If compact is True, only set the value if it's different from what it would be anyway. """ |
# for each interval to render
for i, (s, e, v) in enumerate(self.iterperiods(start, end)):
# look at all intervals included in the current interval
# (always at least 1)
if i == 0:
# if the first, set initial value to new value of range
self.set(s, value, compact)
else:
# otherwise, remove intermediate key
del self[s]
# finish by setting the end of the interval to the previous value
self.set(end, v, compact) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def exists(self):
"""returns False when the timeseries has a None value, True otherwise""" |
result = TimeSeries(default=False if self.default is None else True)
for t, v in self:
result[t] = False if v is None else True
return result |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def iterintervals(self, n=2):
"""Iterate over groups of `n` consecutive measurement points in the time series. """ |
# tee the original iterator into n identical iterators
streams = tee(iter(self), n)
# advance the "cursor" on each iterator by an increasing
# offset, e.g. if n=3:
#
# [a, b, c, d, e, f, ..., w, x, y, z]
# first cursor --> *
# second cursor --> *
# third cursor --> *
for stream_index, stream in enumerate(streams):
for i in range(stream_index):
next(stream)
# now, zip the offset streams back together to yield tuples,
# in the n=3 example it would yield:
# (a, b, c), (b, c, d), ..., (w, x, y), (x, y, z)
for intervals in zip(*streams):
yield intervals |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def sample(self, sampling_period, start=None, end=None, interpolate='previous'):
"""Sampling at regular time periods. """ |
start, end, mask = self._check_boundaries(start, end)
sampling_period = \
self._check_regularization(start, end, sampling_period)
result = []
current_time = start
while current_time <= end:
value = self.get(current_time, interpolate=interpolate)
result.append((current_time, value))
current_time += sampling_period
return result |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def moving_average(self, sampling_period, window_size=None, start=None, end=None, placement='center', pandas=False):
"""Averaging over regular intervals """ |
start, end, mask = self._check_boundaries(start, end)
# default to sampling_period if not given
if window_size is None:
window_size = sampling_period
sampling_period = \
self._check_regularization(start, end, sampling_period)
# convert to datetime if the times are datetimes
full_window = window_size * 1. # convert to float if int or do nothing
half_window = full_window / 2. # divide by 2
if (isinstance(start, datetime.datetime) and
not isinstance(full_window, datetime.timedelta)):
half_window = datetime.timedelta(seconds=half_window)
full_window = datetime.timedelta(seconds=full_window)
result = []
current_time = start
while current_time <= end:
if placement == 'center':
window_start = current_time - half_window
window_end = current_time + half_window
elif placement == 'left':
window_start = current_time
window_end = current_time + full_window
elif placement == 'right':
window_start = current_time - full_window
window_end = current_time
else:
msg = 'unknown placement "{}"'.format(placement)
raise ValueError(msg)
# calculate mean over window and add (t, v) tuple to list
try:
mean = self.mean(window_start, window_end)
except TypeError as e:
if 'NoneType' in str(e):
mean = None
else:
raise e
result.append((current_time, mean))
current_time += sampling_period
# convert to pandas Series if pandas=True
if pandas:
try:
import pandas as pd
except ImportError:
msg = "can't have pandas=True if pandas is not installed"
raise ImportError(msg)
result = pd.Series(
[v for t, v in result],
index=[t for t, v in result],
)
return result |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def mean(self, start=None, end=None, mask=None):
"""This calculated the average value of the time series over the given time range from `start` to `end`, when `mask` is truthy. """ |
return self.distribution(start=start, end=end, mask=mask).mean() |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def distribution(self, start=None, end=None, normalized=True, mask=None):
"""Calculate the distribution of values over the given time range from `start` to `end`. Args: start (orderable, optional):
The lower time bound of when to calculate the distribution. By default, the first time point will be used. end (orderable, optional):
The upper time bound of when to calculate the distribution. By default, the last time point will be used. normalized (bool):
If True, distribution will sum to one. If False and the time values of the TimeSeries are datetimes, the units will be seconds. mask (:obj:`TimeSeries`, optional):
A domain on which to calculate the distribution. Returns: :obj:`Histogram` with the results. """ |
start, end, mask = self._check_boundaries(start, end, mask=mask)
counter = histogram.Histogram()
for start, end, _ in mask.iterperiods(value=True):
for t0, t1, value in self.iterperiods(start, end):
duration = utils.duration_to_number(
t1 - t0,
units='seconds',
)
try:
counter[value] += duration
except histogram.UnorderableElements as e:
counter = histogram.Histogram.from_dict(
dict(counter), key=hash)
counter[value] += duration
# divide by total duration if result needs to be normalized
if normalized:
return counter.normalized()
else:
return counter |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def n_points(self, start=-inf, end=+inf, mask=None, include_start=True, include_end=False, normalized=False):
"""Calculate the number of points over the given time range from `start` to `end`. Args: start (orderable, optional):
The lower time bound of when to calculate the distribution. By default, start is -infinity. end (orderable, optional):
The upper time bound of when to calculate the distribution. By default, the end is +infinity. mask (:obj:`TimeSeries`, optional):
A domain on which to calculate the distribution. Returns: `int` with the result """ |
# just go ahead and return 0 if we already know it regarless
# of boundaries
if not self.n_measurements():
return 0
start, end, mask = self._check_boundaries(start, end, mask=mask)
count = 0
for start, end, _ in mask.iterperiods(value=True):
if include_end:
end_count = self._d.bisect_right(end)
else:
end_count = self._d.bisect_left(end)
if include_start:
start_count = self._d.bisect_left(start)
else:
start_count = self._d.bisect_right(start)
count += (end_count - start_count)
if normalized:
count /= float(self.n_measurements())
return count |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _check_time_series(self, other):
"""Function used to check the type of the argument and raise an informative error message if it's not a TimeSeries. """ |
if not isinstance(other, TimeSeries):
msg = "unsupported operand types(s) for +: %s and %s" % \
(type(self), type(other))
raise TypeError(msg) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def operation(self, other, function, **kwargs):
"""Calculate "elementwise" operation either between this TimeSeries and another one, i.e. operation(t) = function(self(t), other(t)) or between this timeseries and a constant: operation(t) = function(self(t), other) If it's another time series, the measurement times in the resulting TimeSeries will be the union of the sets of measurement times of the input time series. If it's a constant, the measurement times will not change. """ |
result = TimeSeries(**kwargs)
if isinstance(other, TimeSeries):
for time, value in self:
result[time] = function(value, other[time])
for time, value in other:
result[time] = function(self[time], value)
else:
for time, value in self:
result[time] = function(value, other)
return result |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def to_bool(self, invert=False):
"""Return the truth value of each element.""" |
if invert:
def function(x, y):
return False if x else True
else:
def function(x, y):
return True if x else False
return self.operation(None, function) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def read_all(pattern='data/lightbulb-*.csv'):
"""Read all of the CSVs in a directory matching the filename pattern as TimeSeries. """ |
result = []
for filename in glob.iglob(pattern):
print('reading', filename, file=sys.stderr)
ts = traces.TimeSeries.from_csv(
filename,
time_column=0,
time_transform=parse_iso_datetime,
value_column=1,
value_transform=int,
default=0,
)
ts.compact()
result.append(ts)
return result |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def read_dependencies(filename):
"""Read in the dependencies from the virtualenv requirements file. """ |
dependencies = []
filepath = os.path.join('requirements', filename)
with open(filepath, 'r') as stream:
for line in stream:
package = line.strip().split('#')[0].strip()
if package and package.split(' ')[0] != '-r':
dependencies.append(package)
return dependencies |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def process(self, plugin, instance=None, action=None):
"""Given JSON objects from client, perform actual processing Arguments: plugin (dict):
JSON representation of plug-in to process instance (dict, optional):
JSON representation of Instance to be processed. action (str, optional):
Id of action to process """ |
plugin_obj = self.__plugins[plugin["id"]]
instance_obj = (self.__instances[instance["id"]]
if instance is not None else None)
result = pyblish.plugin.process(
plugin=plugin_obj,
context=self._context,
instance=instance_obj,
action=action)
return formatting.format_result(result) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _dispatch(self, method, params):
"""Customise exception handling""" |
self._count += 1
func = getattr(self, method)
try:
return func(*params)
except Exception as e:
traceback.print_exc()
raise e |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def emit(self, signal, kwargs):
"""Trigger registered callbacks This method is triggered remotely and run locally. The keywords "instance" and "plugin" are implicitly converted to their corresponding Pyblish objects. """ |
if "context" in kwargs:
kwargs["context"] = self._context
if "instance" in kwargs:
kwargs["instance"] = self.__instances[kwargs["instance"]]
if "plugin" in kwargs:
kwargs["plugin"] = self.__plugins[kwargs["plugin"]]
pyblish.api.emit(signal, **kwargs) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def resolve_fragment(self, document, fragment):
""" Resolve a ``fragment`` within the referenced ``document``. :argument document: the referrant document :argument str fragment: a URI fragment to resolve within it """ |
fragment = fragment.lstrip(u"/")
parts = unquote(fragment).split(u"/") if fragment else []
for part in parts:
part = part.replace(u"~1", u"/").replace(u"~0", u"~")
if isinstance(document, Sequence):
# Array indexes should be turned into integers
try:
part = int(part)
except ValueError:
pass
try:
document = document[part]
except (TypeError, LookupError):
raise RefResolutionError(
"Unresolvable JSON pointer: %r" % fragment
)
return document |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def generate_safemode_windows():
"""Produce batch file to run QML in safe-mode Usage: $ python -c "import compat;compat.generate_safemode_windows()" $ run.bat """ |
try:
import pyblish
import pyblish_qml
import PyQt5
except ImportError:
return sys.stderr.write(
"Run this in a terminal with access to "
"the Pyblish libraries and PyQt5.\n")
template = r"""@echo off
:: Clear all environment variables
@echo off
if exist ".\backup_env.bat" del ".\backup_env.bat"
for /f "tokens=1* delims==" %%a in ('set') do (
echo set %%a=%%b>> .\backup_env.bat
set %%a=
)
:: Set only the bare essentials
set PATH={PyQt5}
set PATH=%PATH%;{python}
set PYTHONPATH={pyblish}
set PYTHONPATH=%PYTHONPATH%;{pyblish_qml}
set PYTHONPATH=%PYTHONPATH%;{PyQt5}
set SystemRoot=C:\Windows
:: Run Pyblish
python -m pyblish_qml
:: Restore environment
backup_env.bat
"""
values = {}
for lib in (pyblish, pyblish_qml, PyQt5):
values[lib.__name__] = os.path.dirname(os.path.dirname(lib.__file__))
values["python"] = os.path.dirname(sys.executable)
with open("run.bat", "w") as f:
print("Writing %s" % template.format(**values))
f.write(template.format(**values)) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def find_python():
"""Search for Python automatically""" |
python = (
_state.get("pythonExecutable") or
# Support for multiple executables.
next((
exe for exe in
os.getenv("PYBLISH_QML_PYTHON_EXECUTABLE", "").split(os.pathsep)
if os.path.isfile(exe)), None
) or
# Search PATH for executables.
which("python") or
which("python3")
)
if not python or not os.path.isfile(python):
raise ValueError("Could not locate Python executable.")
return python |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def find_pyqt5(python):
"""Search for PyQt5 automatically""" |
pyqt5 = (
_state.get("pyqt5") or
os.getenv("PYBLISH_QML_PYQT5")
)
# If not registered, ask Python for it explicitly
# This avoids having to expose PyQt5 on PYTHONPATH
# where it may otherwise get picked up by bystanders
# such as Python 2.
if not pyqt5:
try:
path = subprocess.check_output([
python, "-c",
"import PyQt5, sys;"
"sys.stdout.write(PyQt5.__file__)"
# Normally, the output is bytes.
], universal_newlines=True)
pyqt5 = os.path.dirname(os.path.dirname(path))
except subprocess.CalledProcessError:
pass
return pyqt5 |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def which(program):
"""Locate `program` in PATH Arguments: program (str):
Name of program, e.g. "python" """ |
def is_exe(fpath):
if os.path.isfile(fpath) and os.access(fpath, os.X_OK):
return True
return False
for path in os.environ["PATH"].split(os.pathsep):
for ext in os.getenv("PATHEXT", "").split(os.pathsep):
fname = program + ext.lower()
abspath = os.path.join(path.strip('"'), fname)
if is_exe(abspath):
return abspath
return None |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def listen(self):
"""Listen to both stdout and stderr We'll want messages of a particular origin and format to cause QML to perform some action. Other messages are simply forwarded, as they are expected to be plain print or error messages. """ |
def _listen():
"""This runs in a thread"""
HEADER = "pyblish-qml:popen.request"
for line in iter(self.popen.stdout.readline, b""):
if six.PY3:
line = line.decode("utf8")
try:
response = json.loads(line)
except Exception:
# This must be a regular message.
sys.stdout.write(line)
else:
if (hasattr(response, "get") and
response.get("header") == HEADER):
payload = response["payload"]
args = payload["args"]
func_name = payload["name"]
wrapper = _state.get("dispatchWrapper",
default_wrapper)
func = getattr(self.service, func_name)
result = wrapper(func, *args) # block..
# Note(marcus): This is where we wait for the host to
# finish. Technically, we could kill the GUI at this
# point which would make the following commands throw
# an exception. However, no host is capable of kill
# the GUI whilst running a command. The host is locked
# until finished, which means we are guaranteed to
# always respond.
data = json.dumps({
"header": "pyblish-qml:popen.response",
"payload": result
})
if six.PY3:
data = data.encode("ascii")
self.popen.stdin.write(data + b"\n")
self.popen.stdin.flush()
else:
# In the off chance that a message
# was successfully decoded as JSON,
# but *wasn't* a request, just print it.
sys.stdout.write(line)
if not self.listening:
self._start_pulse()
if self.modal:
_listen()
else:
thread = threading.Thread(target=_listen)
thread.daemon = True
thread.start()
self.listening = True |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _start_pulse(self):
"""Send pulse to child process Child process will run forever if parent process encounter such failure that not able to kill child process. This inform child process that server is still running and child process will auto kill itself after server stop sending pulse message. """ |
def _pulse():
start_time = time.time()
while True:
data = json.dumps({"header": "pyblish-qml:server.pulse"})
if six.PY3:
data = data.encode("ascii")
try:
self.popen.stdin.write(data + b"\n")
self.popen.stdin.flush()
except IOError:
break
# Send pulse every 5 seconds
time.sleep(5.0 - ((time.time() - start_time) % 5.0))
thread = threading.Thread(target=_pulse)
thread.daemon = True
thread.start() |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def main(demo=False, aschild=False, targets=[]):
"""Start the Qt-runtime and show the window Arguments: aschild (bool, optional):
Run as child of parent process """ |
if aschild:
print("Starting pyblish-qml")
compat.main()
app = Application(APP_PATH, targets)
app.listen()
print("Done, don't forget to call `show()`")
return app.exec_()
else:
print("Starting pyblish-qml server..")
service = ipc.service.MockService() if demo else ipc.service.Service()
server = ipc.server.Server(service, targets=targets)
proxy = ipc.server.Proxy(server)
proxy.show(settings.to_dict())
server.listen()
server.wait() |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def event(self, event):
"""Allow GUI to be closed upon holding Shift""" |
if event.type() == QtCore.QEvent.Close:
modifiers = self.app.queryKeyboardModifiers()
shift_pressed = QtCore.Qt.ShiftModifier & modifiers
states = self.app.controller.states
if shift_pressed:
print("Force quitted..")
self.app.controller.host.emit("pyblishQmlCloseForced")
event.accept()
elif any(state in states for state in ("ready", "finished")):
self.app.controller.host.emit("pyblishQmlClose")
event.accept()
else:
print("Not ready, hold SHIFT to force an exit")
event.ignore()
return super(Window, self).event(event) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def inFocus(self):
"""Set GUI on-top flag""" |
previous_flags = self.window.flags()
self.window.setFlags(previous_flags |
QtCore.Qt.WindowStaysOnTopHint) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def listen(self):
"""Listen on incoming messages from host TODO(marcus):
We can't use this, as we are already listening on stdin through client.py. Do use this, we will have to find a way to receive multiple signals from the same stdin, and channel them to their corresponding source. """ |
def _listen():
while True:
line = self.host.channels["parent"].get()
payload = json.loads(line)["payload"]
# We can't call methods directly, as we are running
# in a thread. Instead, we emit signals that do the
# job for us.
signal = {
"show": "shown",
"hide": "hidden",
"quit": "quitted",
"publish": "published",
"validate": "validated",
"rise": "risen",
"inFocus": "inFocused",
"outFocus": "outFocused",
}.get(payload["name"])
if not signal:
print("'{name}' was unavailable.".format(
**payload))
else:
try:
getattr(self, signal).emit(
*payload.get("args", []))
except Exception:
traceback.print_exc()
thread = threading.Thread(target=_listen)
thread.daemon = True
thread.start() |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def defer(target, args=None, kwargs=None, callback=None):
"""Perform operation in thread with callback Instances are cached until finished, at which point they are garbage collected. If we didn't do this, Python would step in and garbage collect the thread before having had time to finish, resulting in an exception. Arguments: target (callable):
Method or function to call callback (callable, optional):
Method or function to call once `target` has finished. Returns: None """ |
obj = _defer(target, args, kwargs, callback)
obj.finished.connect(lambda: _defer_cleanup(obj))
obj.start()
_defer_threads.append(obj)
return obj |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def schedule(func, time, channel="default"):
"""Run `func` at a later `time` in a dedicated `channel` Given an arbitrary function, call this function after a given timeout. It will ensure that only one "job" is running within the given channel at any one time and cancel any currently running job if a new job is submitted before the timeout. """ |
try:
_jobs[channel].stop()
except (AttributeError, KeyError):
pass
timer = QtCore.QTimer()
timer.setSingleShot(True)
timer.timeout.connect(func)
timer.start(time)
_jobs[channel] = timer |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def format_text(text):
"""Remove newlines, but preserve paragraphs""" |
result = ""
for paragraph in text.split("\n\n"):
result += " ".join(paragraph.split()) + "\n\n"
result = result.rstrip("\n") # Remove last newlines
# converting links to HTML
pattern = r"(https?:\/\/(?:w{1,3}.)?[^\s]*?(?:\.[a-z]+)+)"
pattern += r"(?![^<]*?(?:<\/\w+>|\/?>))"
if re.search(pattern, result):
html = r"<a href='\1'><font color='FF00CC'>\1</font></a>"
result = re.sub(pattern, html, result)
return result |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def SlotSentinel(*args):
"""Provides exception handling for all slots""" |
# (NOTE) davidlatwe
# Thanks to this answer
# https://stackoverflow.com/questions/18740884
if len(args) == 0 or isinstance(args[0], types.FunctionType):
args = []
@QtCore.pyqtSlot(*args)
def slotdecorator(func):
@wraps(func)
def wrapper(*args, **kwargs):
try:
func(*args)
except Exception:
traceback.print_exc()
return wrapper
return slotdecorator |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _byteify(data):
"""Convert unicode to bytes""" |
# Unicode
if isinstance(data, six.text_type):
return data.encode("utf-8")
# Members of lists
if isinstance(data, list):
return [_byteify(item) for item in data]
# Members of dicts
if isinstance(data, dict):
return {
_byteify(key): _byteify(value) for key, value in data.items()
}
# Anything else, return the original form
return data |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def process(self, plugin, context, instance=None, action=None):
"""Transmit a `process` request to host Arguments: plugin (PluginProxy):
Plug-in to process context (ContextProxy):
Filtered context instance (InstanceProxy, optional):
Instance to process action (str, optional):
Action to process """ |
plugin = plugin.to_json()
instance = instance.to_json() if instance is not None else None
return self._dispatch("process", args=[plugin, instance, action]) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _self_destruct(self):
"""Auto quit exec if parent process failed """ |
# This will give parent process 15 seconds to reset.
self._kill = threading.Timer(15, lambda: os._exit(0))
self._kill.start() |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.