code string | signature string | docstring string | loss_without_docstring float64 | loss_with_docstring float64 | factor float64 |
|---|---|---|---|---|---|
try:
assert(G.graph["family"] == "chimera")
m = G.graph["columns"]
n = G.graph["rows"]
t = G.graph["tile"]
coordinates = G.graph["labels"] == "coordinate"
except:
raise ValueError("Target chimera graph needs to have columns, rows, \
tile, and label at... | def draw_chimera_yield(G, **kwargs) | Draws the given graph G with highlighted faults, according to layout.
Parameters
----------
G : NetworkX graph
The graph to be parsed for faults
unused_color : tuple or color string (optional, default (0.9,0.9,0.9,1.0))
The color to use for nodes and edges of G which are not faults.
... | 6.212608 | 6.161531 | 1.00829 |
if G is None:
raise ValueError("Expected NetworkX graph!")
# finding the maximum clique in a graph is equivalent to finding
# the independent set in the complementary graph
complement_G = nx.complement(G)
return dnx.maximum_independent_set(complement_G, sampler, lagrange, **sampler_arg... | def maximum_clique(G, sampler=None, lagrange=2.0, **sampler_args) | Returns an approximate maximum clique.
A clique in an undirected graph G = (V, E) is a subset of the vertex set
`C \subseteq V` such that for every two vertices in C there exists an edge
connecting the two. This is equivalent to saying that the subgraph
induced by C is complete (in some cases, the term ... | 4.816532 | 5.300198 | 0.908746 |
# 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 ... | 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... | 4.968252 | 4.657345 | 1.066756 |
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 = ... | 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 latti... | 2.344289 | 2.465364 | 0.95089 |
i, j, u, k = q
m, n, t = self.args
return ((n*i + j)*2 + u)*t + k | def int(self, q) | Converts the chimera_index `q` into an linear_index
Parameters
----------
q : tuple
The chimera_index node label
Returns
-------
r : int
The linear_index node label corresponding to q | 12.661422 | 11.345951 | 1.115942 |
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 | 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 | 5.416209 | 5.429136 | 0.997619 |
m, n, t = self.args
return (((n*i + j)*2 + u)*t + k for (i, j, u, k) in qlist) | 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 nod... | 11.682414 | 11.337182 | 1.030451 |
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 | 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 nod... | 5.192184 | 5.489171 | 0.945896 |
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 ... | 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,... | 5.194139 | 4.364497 | 1.190089 |
return all(u in G[v] for u, v in itertools.combinations(G[n], 2)) | 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
... | 4.477506 | 9.210176 | 0.486148 |
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 | 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 neighb... | 3.15807 | 5.053149 | 0.624971 |
# 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, ke... | 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 boun... | 3.8398 | 3.854792 | 0.996111 |
# 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_n... | 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 bo... | 6.030385 | 6.273484 | 0.96125 |
# 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_n... | 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 b... | 6.757953 | 6.956438 | 0.971467 |
# 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 tr... | 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... | 4.83842 | 4.810787 | 1.005744 |
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]
... | 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
A dict of the form {v: neighbors, ...} where v are
vertices in a graph and neighbors is a set.
Returns
----------
new_edges: set of edges that were ... | 2.112292 | 2.318691 | 0.910985 |
# 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])
... | 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 ... | 6.067363 | 6.417487 | 0.945442 |
# 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 or... | 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 in... | 6.55627 | 6.799875 | 0.964175 |
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:
... | def _graph_reduction(adj, x, g, f) | we can go ahead and remove any simplicial or almost-simplicial vertices from adj. | 3.731144 | 3.25979 | 1.144596 |
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)
... | 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. | 1.847451 | 1.726842 | 1.069843 |
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])... | def _theorem6p1() | See Theorem 6.1 in paper. | 3.817793 | 3.535603 | 1.079814 |
pruning_set2 = set()
def _prune2(x, a, nbrs_a):
frozen_nbrs_a = frozenset(nbrs_a)
for i in range(len(x)):
key = (tuple(x[0:i]), a, frozen_nbrs_a)
if key in pruning_set2:
return True
return False
def _explored2(x, a, nbrs_a):
prun... | def _theorem6p2() | See Theorem 6.2 in paper.
Prunes (x,...,a) when (x,a) is explored and a has the same neighbour set in both graphs. | 3.184651 | 2.707938 | 1.176043 |
pruning_set3 = set()
def _prune3(x, as_list, b):
for a in as_list:
key = (tuple(x), a, b) # (s,a,b) with (s,a) explored
if key in pruning_set3:
return True
return False
def _explored3(x, a, as_list):
for b in as_list:
prunab... | def _theorem6p3() | See Theorem 6.3 in paper.
Prunes (s,b) when (s,a) is explored, b (almost) simplicial in (s,a), and a (almost) simplicial in (s,b) | 3.541794 | 2.928783 | 1.209306 |
pruning_set4 = list()
def _prune4(edges_b):
for edges_a in pruning_set4:
if edges_a.issubset(edges_b):
return True
return False
def _explored4(edges_a):
pruning_set4.append(edges_a) # (s,E_a) with (s,a) explored
return _prune4, _explored4 | def _theorem6p4() | See Theorem 6.4 in paper.
Let E(x) denote the edges added when eliminating x. (edges_x below).
Prunes (s,b) when (s,a) is explored and E(a) is a subset of E(b).
For this theorem we only record E(a) rather than (s,E(a))
because we only need to check for pruning in the same s context
(i.e the same lev... | 5.87558 | 3.637833 | 1.615132 |
try:
import matplotlib.pyplot as plt
import matplotlib as mpl
except ImportError:
raise ImportError("Matplotlib and numpy required for draw_chimera()")
nodelist = G.nodes()
edgelist = G.edges()
faults_nodelist = perfect_graph.nodes() - nodelist
faults_edgelist = pe... | def draw_yield(G, layout, perfect_graph, unused_color=(0.9,0.9,0.9,1.0),
fault_color=(1.0,0.0,0.0,1.0), fault_shape='x',
fault_style='dashed', **kwargs) | Draws the given graph G with highlighted faults, according to layout.
Parameters
----------
G : NetworkX graph
The graph to be parsed for faults
layout : dict
A dict of coordinates associated with each node in perfect_graph. Should
be of the form {node: coordinate, ...}. Coord... | 2.380604 | 2.294664 | 1.037452 |
# 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)
... | def _minimum_coloring_qubo(x_vars, chi_lb, chi_ub, magnitude=1.) | We want to disincentivize unneeded colors. Generates the QUBO
that does that. | 4.978868 | 4.131921 | 1.204977 |
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 | 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. | 2.299231 | 2.582537 | 0.890299 |
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
retu... | 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. | 2.157793 | 2.39104 | 0.902449 |
# 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 boun... | 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
... | 4.27354 | 3.482102 | 1.227288 |
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:
... | 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 cons... | 4.310565 | 5.308339 | 0.812036 |
return all(coloring[u] != coloring[v] for u, v in G.edges) | 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
{node: color, ...}.
Returns
---... | 2.894404 | 6.739141 | 0.429492 |
# 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 tho... | 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 viola... | 4.594186 | 4.52348 | 1.015631 |
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... | 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.
... | 4.198218 | 5.642886 | 0.743984 |
edge_mapping = {edge: idx for idx, edge in enumerate(G.edges)}
edge_mapping.update({(e1, e0): idx for (e0, e1), idx in edge_mapping.items()})
return edge_mapping | def _edge_mapping(G) | Assigns a variable for each edge in G.
(u, v) and (v, u) map to the same variable. | 2.439237 | 2.736082 | 0.891507 |
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:
... | 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 | 2.371689 | 2.354353 | 1.007363 |
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]
#... | 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 | 5.828958 | 5.575002 | 1.045553 |
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... | 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 th... | 2.548948 | 2.512883 | 1.014352 |
# 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 sp... | 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 maximu... | 5.358132 | 6.81252 | 0.786513 |
return maximum_weighted_independent_set(G, None, sampler, lagrange, **sampler_args) | 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 ... | 3.946811 | 9.113861 | 0.433056 |
# 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
... | 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 a... | 6.35246 | 6.419474 | 0.989561 |
indep_nodes = set(maximum_weighted_independent_set(G, weight, sampler, **sampler_args))
return [v for v in G if v not in indep_nodes] | 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 minim... | 4.13534 | 6.08091 | 0.680053 |
cover = set(vertex_cover)
return all(u in cover or v in cover for u, v in G.edges) | 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... | 3.754996 | 10.764668 | 0.348826 |
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=di... | 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 : flo... | 3.630651 | 3.618965 | 1.003229 |
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
... | 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.)
Scal... | 4.709238 | 4.456603 | 1.056688 |
draw_qubit_graph(G, pegasus_layout(G, crosses=crosses), **kwargs) | 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.
lin... | 6.260893 | 19.080513 | 0.32813 |
crosses = kwargs.pop("crosses", False)
draw_embedding(G, pegasus_layout(G, crosses=crosses), *args, **kwargs) | 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
----------
... | 4.829201 | 8.54279 | 0.565296 |
try:
assert(G.graph["family"] == "pegasus")
m = G.graph['columns']
offset_lists = (G.graph['vertical_offsets'], G.graph['horizontal_offsets'])
coordinates = G.graph["labels"] == "coordinate"
# Can't interpret fabric_only from graph attributes
except:
raise Va... | def draw_pegasus_yield(G, **kwargs) | Draws the given graph G with highlighted faults, according to layout.
Parameters
----------
G : NetworkX graph
The graph to be parsed for faults
unused_color : tuple or color string (optional, default (0.9,0.9,0.9,1.0))
The color to use for nodes and edges of G which are not faults.
... | 10.34702 | 10.19131 | 1.015279 |
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)
... | 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. | 2.728137 | 2.755527 | 0.99006 |
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... | def convert_args_to_list(args) | Convert all iterable pairs of inputs into a list of list | 2.113234 | 2.03356 | 1.03918 |
def done(a, b, inclusive_end):
if inclusive_end:
return a <= b
else:
return a < b
current = start_dt
while done(current, end_dt, inclusive_end):
yield current
current += datetime.timedelta(**{unit: n_units}) | def datetime_range(start_dt, end_dt, unit,
n_units=1, inclusive_end=False) | A range of datetimes/dates. | 2.789676 | 2.857368 | 0.97631 |
if unit == 'years':
new_year = dt.year - (dt.year - 1) % n_units
return datetime.datetime(new_year, 1, 1, 0, 0, 0)
elif unit == 'months':
new_month = dt.month - (dt.month - 1) % n_units
return datetime.datetime(dt.year, new_month, 1, 0, 0, 0)
elif unit == 'weeks':
... | def floor_datetime(dt, unit, n_units=1) | Floor a datetime to nearest n units. For example, if we want to
floor to nearest three months, starting with 2016-05-06-yadda, it
will go to 2016-04-01. Or, if starting with 2016-05-06-11:45:06
and rounding to nearest fifteen minutes, it will result in
2016-05-06-11:45:00. | 1.383961 | 1.389812 | 0.99579 |
it = iter(iterable)
a = next(it, None)
for b in it:
yield (a, b)
a = b | def pairwise(iterable) | given an interable `p1, p2, p3, ...`
it iterates through pairwise tuples `(p0, p1), (p1, p2), ...` | 2.59731 | 4.141635 | 0.627122 |
_self = self._discard_value(None)
if not _self.total():
return None
weighted_sum = sum(
key * value for key, value in iteritems(_self)
)
return weighted_sum / float(_self.total()) | def mean(self) | Mean of the distribution. | 8.508545 | 7.987054 | 1.065292 |
_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()) | def variance(self) | Variance of the distribution. | 6.391283 | 5.985155 | 1.067856 |
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[v... | def normalized(self) | Return a normalized version of the histogram where the values sum
to one. | 5.283498 | 4.284123 | 1.233274 |
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
... | def _quantile_function(self, alpha=0.5, smallest_count=None) | Return a function that returns the quantile values for this
histogram. | 2.383647 | 2.348609 | 1.014919 |
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(ms... | def get(self, time, interpolate='previous') | Get the value of the time series, even in-between measured values. | 3.595359 | 3.759254 | 0.956402 |
if (len(self) == 0) or (not compact) or \
(compact and self.get(time) != value):
self._d[time] = value | 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. | 5.079412 | 4.802305 | 1.057703 |
# 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
... | 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. | 6.989696 | 7.376656 | 0.947543 |
previous_value = object()
redundant = []
for time, value in self:
if value == previous_value:
redundant.append(time)
previous_value = value
for time in redundant:
del self[time] | def compact(self) | Convert this instance to a compact version: the value will be the
same at all times, but repeated measurements are discarded. | 4.190723 | 3.686874 | 1.13666 |
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 | def exists(self) | returns False when the timeseries has a None value,
True otherwise | 7.982057 | 5.924057 | 1.347397 |
for s, e, v in self.iterperiods(start, end):
try:
del self._d[s]
except KeyError:
pass | def remove_points_from_interval(self, start, end) | Allow removal of all points from the time series within a interval
[start:end]. | 6.608163 | 6.07707 | 1.087393 |
# 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 --> *
#... | def iterintervals(self, n=2) | Iterate over groups of `n` consecutive measurement points in the
time series. | 6.215186 | 6.504601 | 0.955506 |
start, end, mask = \
self._check_boundaries(start, end, allow_infinite=False)
value_function = self._value_function(value)
# get start index and value
start_index = self._d.bisect_right(start)
if start_index:
start_value = self._d[self._d.iloc[s... | def iterperiods(self, start=None, end=None, value=None) | This iterates over the periods (optionally, within a given time
span) and yields (interval start, interval end, value) tuples.
TODO: add mask argument here. | 3.286462 | 3.022781 | 1.087231 |
start, end, mask = \
self._check_boundaries(start, end, allow_infinite=True)
result = TimeSeries(default=self.default)
for t0, t1, value in self.iterperiods(start, end):
result[t0] = value
result[t1] = self[t1]
return result | def slice(self, start, end) | Return an equivalent TimeSeries that only has points between
`start` and `end` (always starting at `start`) | 5.172989 | 4.59072 | 1.126836 |
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)... | def sample(self, sampling_period, start=None, end=None,
interpolate='previous') | Sampling at regular time periods. | 3.214232 | 3.209038 | 1.001619 |
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 datet... | def moving_average(self, sampling_period,
window_size=None,
start=None, end=None,
placement='center',
pandas=False) | Averaging over regular intervals | 2.444999 | 2.435901 | 1.003735 |
return self.distribution(start=start, end=end, mask=mask).mean() | 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. | 4.837308 | 5.6994 | 0.84874 |
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(
t... | 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, o... | 5.419663 | 5.638376 | 0.96121 |
# 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):
... | 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 t... | 3.227971 | 3.462922 | 0.932152 |
if not isinstance(other, TimeSeries):
msg = "unsupported operand types(s) for +: %s and %s" % \
(type(self), type(other))
raise TypeError(msg) | 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. | 2.951391 | 2.670207 | 1.105304 |
# cast to list since this is getting iterated over several
# times (causes problem if timeseries_list is a generator)
timeseries_list = list(timeseries_list)
# Create iterators for each timeseries and then add the first
# item from each iterator onto a priority queue. T... | def _iter_merge(timeseries_list) | This function uses a priority queue to efficiently yield the (time,
value_list) tuples that occur from merging together many time
series. | 4.07407 | 3.886977 | 1.048133 |
# using return without an argument is the way to say "the
# iterator is empty" when there is nothing to iterate over
# (the more you know...)
if not timeseries_list:
return
# for ts in timeseries_list:
# if ts.is_floating():
# msg... | def iter_merge(cls, timeseries_list) | Iterate through several time series in order, yielding (time, list)
tuples where list is the values of each individual TimeSeries
in the list at time t. | 6.242669 | 5.966712 | 1.046249 |
# If operation is not given then the default is the list
# of defaults of all time series
# If operation is given, then the default is the result of
# the operation over the list of all defaults
default = [ts.default for ts in ts_list]
if operation:
d... | def merge(cls, ts_list, compact=True, operation=None) | Iterate through several time series in order, yielding (time,
`value`) where `value` is the either the list of each
individual TimeSeries in the list at time t (in the same order
as in ts_list) or the result of the optional `operation` on
that list of values. | 4.048718 | 3.541893 | 1.143095 |
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, v... | 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
... | 2.161175 | 1.995197 | 1.083189 |
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) | def to_bool(self, invert=False) | Return the truth value of each element. | 3.788418 | 3.322107 | 1.140366 |
if inclusive:
def function(x, y):
return True if x >= y else False
else:
def function(x, y):
return True if x > y else False
return self.operation(value, function) | def threshold(self, value, inclusive=False) | Return True if > than treshold value (or >= threshold value if
inclusive=True). | 3.13879 | 3.282223 | 0.9563 |
return TimeSeries.merge(
[self, other], operation=operations.ignorant_sum
) | def sum(self, other) | sum(x, y) = x(t) + y(t). | 22.699331 | 20.864416 | 1.087945 |
return self.operation(other, lambda x, y: x - y) | def difference(self, other) | difference(x, y) = x(t) - y(t). | 6.802165 | 6.720491 | 1.012153 |
return self.operation(other, lambda x, y: x * y) | def multiply(self, other) | mul(t) = self(t) * other(t). | 6.367679 | 5.956878 | 1.068962 |
return self.operation(other, lambda x, y: int(x and y)) | def logical_and(self, other) | logical_and(t) = self(t) and other(t). | 6.551274 | 7.300387 | 0.897387 |
return self.operation(other, lambda x, y: int(x or y)) | def logical_or(self, other) | logical_or(t) = self(t) or other(t). | 6.189737 | 7.033649 | 0.880018 |
return self.operation(other, lambda x, y: int(bool(x) ^ bool(y))) | def logical_xor(self, other) | logical_xor(t) = self(t) ^ other(t). | 4.470946 | 4.776977 | 0.935936 |
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,
... | def read_all(pattern='data/lightbulb-*.csv') | Read all of the CSVs in a directory matching the filename pattern
as TimeSeries. | 3.955646 | 3.602389 | 1.098062 |
filename = os.path.join("traces", "__init__.py")
result = None
with open(filename) as stream:
for line in stream:
if key in line:
result = line.split('=')[-1].strip().replace("'", "")
# throw error if version isn't in __init__ file
if result is None:
... | def read_init(key) | Parse the package __init__ file to find a variable so that it's not
in multiple places. | 3.8416 | 3.620551 | 1.061054 |
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 ... | def read_dependencies(filename) | Read in the dependencies from the virtualenv requirements file. | 2.630998 | 2.467468 | 1.066274 |
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,
... | 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 | 4.630403 | 4.463447 | 1.037405 |
self._count += 1
func = getattr(self, method)
try:
return func(*params)
except Exception as e:
traceback.print_exc()
raise e | def _dispatch(self, method, params) | Customise exception handling | 3.678734 | 3.408575 | 1.079259 |
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... | 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. | 3.097915 | 2.316117 | 1.337547 |
def _validates(cls):
validators[version] = cls
if u"id" in cls.META_SCHEMA:
meta_schemas[cls.META_SCHEMA[u"id"]] = cls
return cls
return _validates | def validates(version) | Register the decorated validator for a ``version`` of the specification.
Registered validators and their meta schemas will be considered when
parsing ``$schema`` properties' URIs.
:argument str version: an identifier to use as the version's name
:returns: a class decorator to decorate the validator wi... | 6.586374 | 4.714239 | 1.397124 |
if cls is None:
cls = validator_for(schema)
cls.check_schema(schema)
cls(schema, *args, **kwargs).validate(instance) | def validate(instance, schema, cls=None, *args, **kwargs) | Validate an instance under the given schema.
>>> validate([2, 3, 4], {"maxItems" : 2})
Traceback (most recent call last):
...
ValidationError: [2, 3, 4] is too long
:func:`validate` will first verify that the provided schema is itself
valid, since not doing so can lead to l... | 3.048749 | 6.575139 | 0.463678 |
return cls(schema.get(u"id", u""), schema, *args, **kwargs) | def from_schema(cls, schema, *args, **kwargs) | Construct a resolver from a JSON schema object.
:argument schema schema: the referring schema
:rtype: :class:`RefResolver` | 7.518102 | 6.590774 | 1.140701 |
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 integer... | 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 | 3.277275 | 3.29934 | 0.993312 |
scheme = urlsplit(uri).scheme
if scheme in self.handlers:
result = self.handlers[scheme](uri)
elif (
scheme in [u"http", u"https"] and
requests and
getattr(requests.Response, "json", None) is not None
):
# Requests ha... | def resolve_remote(self, uri) | Resolve a remote ``uri``.
Does not check the store first, but stores the retrieved document in
the store if :attr:`RefResolver.cache_remote` is True.
.. note::
If the requests_ library is present, ``jsonschema`` will use it to
request the remote ``uri``, so that the co... | 3.782809 | 3.043025 | 1.243108 |
errors = dict()
for test in (test_architecture,
test_pyqt_availability,
test_pyblish_availability,
test_qtconf_availability,
test_qtconf_correctness,
test_qt_availability):
try:
test()
except E... | def validate() | Validate compatibility with environment and Pyblish QML | 4.023778 | 3.763576 | 1.069137 |
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
values = {}
for lib in (pyblish, pyblish_qml, ... | def generate_safemode_windows() | Produce batch file to run QML in safe-mode
Usage:
$ python -c "import compat;compat.generate_safemode_windows()"
$ run.bat | 4.546669 | 4.27071 | 1.064617 |
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.... | def find_python() | Search for Python automatically | 4.520513 | 4.443851 | 1.017251 |
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:
... | def find_pyqt5(python) | Search for PyQt5 automatically | 5.870824 | 5.665767 | 1.036192 |
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 = ... | def which(program) | Locate `program` in PATH
Arguments:
program (str): Name of program, e.g. "python" | 2.168101 | 2.196939 | 0.986873 |
def _listen():
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)
... | 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. | 5.138193 | 4.947649 | 1.038512 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.