Code stringlengths 103 85.9k | Summary listlengths 0 94 |
|---|---|
Please provide a description of the function:def embed_ising(source_h, source_J, embedding, target_adjacency, chain_strength=1.0):
source_bqm = dimod.BinaryQuadraticModel.from_ising(source_h, source_J)
target_bqm = embed_bqm(source_bqm, embedding, target_adjacency, chain_strength=chain_strength)
target... | [
"Embed an Ising problem onto a target graph.\n\n Args:\n source_h (dict[variable, bias]/list[bias]):\n Linear biases of the Ising problem. If a list, the list's indices are used as\n variable labels.\n\n source_J (dict[(variable, variable), bias]):\n Quadratic biase... |
Please provide a description of the function:def embed_qubo(source_Q, embedding, target_adjacency, chain_strength=1.0):
source_bqm = dimod.BinaryQuadraticModel.from_qubo(source_Q)
target_bqm = embed_bqm(source_bqm, embedding, target_adjacency, chain_strength=chain_strength)
target_Q, __ = target_bqm.to... | [
"Embed a QUBO onto a target graph.\n\n Args:\n source_Q (dict[(variable, variable), bias]):\n Coefficients of a quadratic unconstrained binary optimization (QUBO) model.\n\n embedding (dict):\n Mapping from source graph to target graph as a dict of form {s: {t, ...}, ...},\n ... |
Please provide a description of the function:def unembed_sampleset(target_sampleset, embedding, source_bqm,
chain_break_method=None, chain_break_fraction=False):
if chain_break_method is None:
chain_break_method = majority_vote
variables = list(source_bqm)
try:
c... | [
"Unembed the samples set.\n\n Construct a sample set for the source binary quadratic model (BQM) by\n unembedding the given samples from the target BQM.\n\n Args:\n target_sampleset (:obj:`dimod.SampleSet`):\n SampleSet from the target BQM.\n\n embedding (dict):\n Mappin... |
Please provide a description of the function:def _adjacency_to_edges(adjacency):
edges = set()
for u in adjacency:
for v in adjacency[u]:
try:
edge = (u, v) if u <= v else (v, u)
except TypeError:
# Py3 does not allow sorting of unlike types
... | [
"determine from an adjacency the list of edges\n if (u, v) in edges, then (v, u) should not be"
] |
Please provide a description of the function:def _embed_state(embedding, state):
return {u: state[v] for v, chain in embedding.items() for u in chain} | [
"Embed a single state/sample by spreading it's values over the chains in the embedding"
] |
Please provide a description of the function:def parameters(self):
param = self.child.parameters.copy()
param['chain_strength'] = []
param['chain_break_fraction'] = []
return param | [
"dict[str, list]: Parameters in the form of a dict.\n\n For an instantiated composed sampler, keys are the keyword parameters accepted by the child sampler\n and parameters added by the composite such as those related to chains.\n\n Examples:\n This example views parameters of a comp... |
Please provide a description of the function:def sample(self, bqm, chain_strength=1.0, chain_break_fraction=True, **parameters):
# solve the problem on the child system
child = self.child
# apply the embedding to the given problem to map it to the child sampler
__, target_edge... | [
"Sample from the provided binary quadratic model.\n\n Also set parameters for handling a chain, the set of vertices in a target graph that\n represents a source-graph vertex; when a D-Wave system is the sampler, it is a set\n of qubits that together represent a variable of the binary quadratic ... |
Please provide a description of the function:def sample(self, bqm, chain_strength=1.0, chain_break_fraction=True, **parameters):
# solve the problem on the child system
child = self.child
# apply the embedding to the given problem to map it to the child sampler
__, __, target_... | [
"Sample from the provided binary quadratic model.\n\n Also set parameters for handling a chain, the set of vertices in a target graph that\n represents a source-graph vertex; when a D-Wave system is the sampler, it is a set\n of qubits that together represent a variable of the binary quadratic ... |
Please provide a description of the function:def sample(self, bqm, chain_strength=1.0, chain_break_fraction=True, **parameters):
if self.embedding is None:
# Find embedding
child = self.child # Solve the problem on the child system
__, target_edgelist, target_adjac... | [
"Sample the binary quadratic model.\n\n Note: At the initial sample(..) call, it will find a suitable embedding and initialize the remaining attributes\n before sampling the bqm. All following sample(..) calls will reuse that initial embedding.\n\n Args:\n bqm (:obj:`dimod.BinaryQuad... |
Please provide a description of the function:def _accumulate_random(count, found, oldthing, newthing):
if randint(1, count + found) <= found:
return count + found, newthing
else:
return count + found, oldthing | [
"This performs on-line random selection.\n\n We have a stream of objects\n\n o_1,c_1; o_2,c_2; ...\n\n where there are c_i equivalent objects like o_1. We'd like to pick\n a random object o uniformly at random from the list\n\n [o_1]*c_1 + [o_2]*c_2 + ...\n\n (actually, this algorithm all... |
Please provide a description of the function:def _bulk_to_linear(M, N, L, qubits):
"Converts a list of chimera coordinates to linear indices."
return [2 * L * N * x + 2 * L * y + L * u + k for x, y, u, k in qubits] | [] |
Please provide a description of the function:def _to_linear(M, N, L, q):
"Converts a qubit in chimera coordinates to its linear index."
(x, y, u, k) = q
return 2 * L * N * x + 2 * L * y + L * u + k | [] |
Please provide a description of the function:def _bulk_to_chimera(M, N, L, qubits):
"Converts a list of linear indices to chimera coordinates."
return [(q // N // L // 2, (q // L // 2) % N, (q // L) % 2, q % L) for q in qubits] | [] |
Please provide a description of the function:def _to_chimera(M, N, L, q):
"Converts a qubit's linear index to chimera coordinates."
return (q // N // L // 2, (q // L // 2) % N, (q // L) % 2, q % L) | [] |
Please provide a description of the function:def _chimera_neighbors(M, N, L, q):
"Returns a list of neighbors of (x,y,u,k) in a perfect :math:`C_{M,N,L}`"
(x, y, u, k) = q
n = [(x, y, 1 - u, l) for l in range(L)]
if u == 0:
if x:
n.append((x - 1, y, u, k))
if x < M - 1:
... | [] |
Please provide a description of the function:def random_processor(M, N, L, qubit_yield, num_evil=0):
# replacement for lambda in edge filter below that works with bot h
def edge_filter(pq):
# we have to unpack the (p,q) edge
p, q = pq
return q in qubits and p < q
qubits = [(x, ... | [
"A utility function that generates a random :math:`C_{M,N,L}` missing some\n percentage of its qubits.\n\n INPUTS:\n M,N,L: the chimera parameters\n qubit_yield: ratio (0 <= qubit_yield <= 1) of #{qubits}/(2*M*N*L)\n num_evil: number of broken in-cell couplers between working qubits\n\n ... |
Please provide a description of the function:def vline_score(self, x, ymin, ymax):
return self._vline_score[x, ymin, ymax] | [
"Returns the number of unbroken paths of qubits\n\n >>> [(x,y,1,k) for y in range(ymin,ymax+1)]\n\n for :math:`k = 0,1,\\cdots,L-1`. This is precomputed for speed.\n "
] |
Please provide a description of the function:def hline_score(self, y, xmin, xmax):
return self._hline_score[y, xmin, xmax] | [
"Returns the number of unbroken paths of qubits\n\n >>> [(x,y,0,k) for x in range(xmin,xmax+1)]\n\n for :math:`k = 0,1,\\cdots,L-1`. This is precomputed for speed.\n "
] |
Please provide a description of the function:def _compute_vline_scores(self):
M, N, L = self.M, self.N, self.L
vline_score = {}
for x in range(M):
laststart = [0 if (x, 0, 1, k) in self else None for k in range(L)]
for y in range(N):
block = [0] *... | [
"Does the hard work to prepare ``vline_score``.\n "
] |
Please provide a description of the function:def _compute_hline_scores(self):
M, N, L = self.M, self.N, self.L
hline_score = {}
for y in range(N):
laststart = [0 if (0, y, 0, k) in self else None for k in range(L)]
for x in range(M):
block = [0] *... | [
"Does the hard work to prepare ``hline_score``.\n "
] |
Please provide a description of the function:def _compute_biclique_sizes(self, recompute=False):
if recompute or not self._biclique_size_computed:
self._biclique_size = {}
self._biclique_size_to_length = defaultdict(dict)
self._biclique_length_to_size = defaultdict(d... | [
"Calls ``self.biclique_size(...)`` for every rectangle contained in this\n processor, to fill the biclique size cache.\n\n INPUTS:\n recompute: if ``True``, then we dump the existing cache and compute\n all biclique sizes from scratch. (default: ``False``)\n "
] |
Please provide a description of the function:def biclique_size(self, xmin, xmax, ymin, ymax):
try:
return self._biclique_size[xmin, xmax, ymin, ymax]
except KeyError:
hscore = self.hline_score(ymin, xmin, xmax)
vscore = self.vline_score(xmin, ymin, ymax)
... | [
"Returns the size parameters ``(m,n)`` of the complete bipartite graph\n :math:`K_{m,n}` comprised of ``m`` unbroken chains of horizontally-aligned qubits\n and ``n`` unbroken chains of vertically-aligned qubits (known as line\n bundles)\n\n INPUTS:\n xmin,xmax,ymin,ymax: inte... |
Please provide a description of the function:def biclique(self, xmin, xmax, ymin, ymax):
Aside = sum((self.maximum_hline_bundle(y, xmin, xmax)
for y in range(ymin, ymax + 1)), [])
Bside = sum((self.maximum_vline_bundle(x, ymin, ymax)
for x in range(xmi... | [
"Compute a maximum-sized complete bipartite graph contained in the\n rectangle defined by ``xmin, xmax, ymin, ymax`` where each chain of\n qubits is either a vertical line or a horizontal line.\n\n INPUTS:\n xmin,xmax,ymin,ymax: integers defining the bounds of a rectangle\n ... |
Please provide a description of the function:def _contains_line(self, line):
return all(v in self for v in line) and all(u in self[v] for u, v in zip(line, line[1::])) | [
"Test if a chain of qubits is completely contained in ``self``. In\n particular, test if all qubits are present and the couplers\n connecting those qubits are also connected.\n\n NOTE: this function assumes that ``line`` is a list or tuple of\n qubits which satisfies the precondition th... |
Please provide a description of the function:def maximum_vline_bundle(self, x0, y0, y1):
y_range = range(y1, y0 - 1, -1) if y0 < y1 else range(y1, y0 + 1)
vlines = [[(x0, y, 1, k) for y in y_range] for k in range(self.L)]
return list(filter(self._contains_line, vlines)) | [
"Compute a maximum set of vertical lines in the unit cells ``(x0,y)``\n for :math:`y0 \\leq y \\leq y1`.\n\n INPUTS:\n y0,x0,x1: int\n\n OUTPUT:\n list of lists of qubits\n "
] |
Please provide a description of the function:def maximum_hline_bundle(self, y0, x0, x1):
x_range = range(x0, x1 + 1) if x0 < x1 else range(x0, x1 - 1, -1)
hlines = [[(x, y0, 0, k) for x in x_range] for k in range(self.L)]
return list(filter(self._contains_line, hlines)) | [
"Compute a maximum set of horizontal lines in the unit cells ``(x,y0)``\n for :math:`x0 \\leq x \\leq x1`.\n\n INPUTS:\n y0,x0,x1: int\n\n OUTPUT:\n list of lists of qubits\n "
] |
Please provide a description of the function:def maximum_ell_bundle(self, ell):
(x0, x1, y0, y1) = ell
hlines = self.maximum_hline_bundle(y0, x0, x1)
vlines = self.maximum_vline_bundle(x0, y0, y1)
if self.random_bundles:
shuffle(hlines)
shuffle(vlines)
... | [
"Return a maximum ell bundle in the rectangle bounded by\n\n :math:`\\{x0,x1\\} \\\\times \\{y0,y1\\}`\n\n with vertical component\n\n :math:`(x0,y0) ... (x0,y1) = {x0} \\\\times \\{y0,...,y1\\}`\n\n and horizontal component\n\n :math:`(x0,y0) ... (x1,y0) = \\{x0,...,x... |
Please provide a description of the function:def _combine_clique_scores(self, rscore, hbar, vbar):
(y0, xmin, xmax) = hbar
(x0, ymin, ymax) = vbar
if rscore is None:
rscore = 0
hscore = self.hline_score(y0, xmin, xmax)
vscore = self.vline_score(x0, ymin, ymax... | [
"Computes the score of a partial native clique embedding given the score\n attained by the already-placed ells, together with the ell block\n defined by ``hbar = (y0,xmin,xmax)``, and ``vbar = (x0,ymin,ymax)``.\n\n In the plain :class:`eden_processor` class, this is simply the number of ells\n... |
Please provide a description of the function:def maxCliqueWithRectangle(self, R, maxCWR):
(xmin, xmax, ymin, ymax) = R
best = nothing = 0, None, None, 1
bestscore = None
count = 0
N = self.N
Xlist = (xmin, xmax, xmin + 1, xmax), (xmax, xmin, xmin, xmax - 1)
... | [
"This does the dirty work for :func:`nativeCliqueEmbed`. Not meant to be\n understood or called on its own. Guaranteed to maintain the inductive\n hypothesis that ``maxCWR`` is optimal. We put in the tiniest amount of\n effort to return a uniform random choice of a maximum-sized native\n ... |
Please provide a description of the function:def nativeCliqueEmbed(self, width):
maxCWR = {}
M, N = self.M, self.N
maxscore = None
count = 0
key = None
for w in range(width + 2):
h = width - w - 2
for ymin in range(N - h):
... | [
"Compute a maximum-sized native clique embedding in an induced\n subgraph of chimera with all chainlengths ``width+1``.\n\n INPUTS:\n width: width of the squares to search, also `chainlength`-1\n\n OUTPUT:\n score: the score for the returned clique (just ``len(clique)``\n ... |
Please provide a description of the function:def largestNativeClique(self, max_chain_length=None):
bigclique = []
bestscore = None
if max_chain_length is None:
wmax = min(self.M, self.N)
else:
wmax = max_chain_length - 1
for w in range(wmax + 1):... | [
"Returns the largest native clique embedding we can find on the\n processor, with the shortest chainlength possible (for that\n clique size).\n\n OUTPUT:\n score: the score for the returned clique (just ``len(clique)``\n in the class :class:`eden_processor`; may differ in ... |
Please provide a description of the function:def largestNativeBiClique(self, chain_imbalance=0, max_chain_length=None):
self._compute_biclique_sizes()
Len2Siz = self._biclique_length_to_size
Siz2Len = self._biclique_size_to_length
overkill = self.M + self.N
if max_chain_... | [
"Returns a native embedding for the complete bipartite graph :math:`K_{n,m}`\n for :math:`n \\leq m`; where :math:`n` is as large as possible and :math:`m` is as large as\n possible subject to :math:`n`. The native embedding of a complete bipartite\n graph is a set of horizontally-aligned qubi... |
Please provide a description of the function:def _compute_all_deletions(self):
minimum_evil = []
for disabled_qubits in map(set, product(*self._evil)):
newmin = []
for s in minimum_evil:
if s < disabled_qubits:
break
el... | [
"Returns all minimal edge covers of the set of evil edges.\n "
] |
Please provide a description of the function:def _subprocessor(self, disabled_qubits):
edgelist = [(p, q) for p, q in self._edgelist if
p not in disabled_qubits and
q not in disabled_qubits]
return eden_processor(edgelist, self.M, self.N, self.L, random_b... | [
"Create a subprocessor by deleting a set of qubits. We assume\n this removes all evil edges, and return an :class:`eden_processor`\n instance.\n "
] |
Please provide a description of the function:def _compute_deletions(self):
M, N, L, edgelist = self.M, self.N, self.L, self._edgelist
if 2**len(self._evil) <= self._proc_limit:
deletions = self._compute_all_deletions()
self._processors = [self._subprocessor(d) for d in d... | [
"If there are fewer than self._proc_limit possible deletion\n sets, compute all subprocessors obtained by deleting a\n minimal subset of qubits.\n "
] |
Please provide a description of the function:def _random_subprocessor(self):
deletion = set()
for e in self._evil:
if e[0] in deletion or e[1] in deletion:
continue
deletion.add(choice(e))
return self._subprocessor(deletion) | [
"Creates a random subprocessor where there is a coupler between\n every pair of working qubits on opposite sides of the same cell.\n This is guaranteed to be minimal in that adding a qubit back in\n will reintroduce a bad coupler, but not to have minimum size.\n\n OUTPUT:\n an... |
Please provide a description of the function:def _random_subprocessors(self):
if self._processors is not None:
return (p for p in self._processors)
elif 2**len(self._evil) <= 8 * self._proc_limit:
deletions = self._compute_all_deletions()
if len(deletions) > ... | [
"Produces an iterator of subprocessors. If there are fewer than\n self._proc_limit subprocessors to consider (by knocking out a\n minimal subset of working qubits incident to broken couplers),\n we work exhaustively. Otherwise, we generate a random set of\n ``self._proc_limit`` subproc... |
Please provide a description of the function:def _map_to_processors(self, f, objective):
P = self._random_subprocessors()
best = f(next(P))
for p in P:
x = f(p)
if objective(best, x):
best = x
return best[1] | [
"Map a function to a list of processors, and return the output that\n best satisfies a transitive objective function. The list of\n processors will differ according to the number of evil qubits and\n :func:`_proc_limit`, see details in :func:`self._random_subprocessors`.\n\n INPUT:\n ... |
Please provide a description of the function:def _objective_bestscore(self, old, new):
(oldscore, oldthing) = old
(newscore, newthing) = new
if oldscore is None:
return True
if newscore is None:
return False
return oldscore < newscore | [
"An objective function that returns True if new has a better score\n than old, and ``False`` otherwise.\n\n INPUTS:\n old (tuple): a tuple (score, embedding)\n\n new (tuple): a tuple (score, embedding)\n\n "
] |
Please provide a description of the function:def _objective_qubitcount(self, old, new):
(oldscore, oldthing) = old
(newscore, newthing) = new
def measure(chains):
return sum(map(len, chains))
if oldscore is None:
return True
if newscore is None:... | [
"An objective function that returns True if new uses fewer qubits\n than old, and False otherwise. This objective function should only be\n used to compare embeddings of the same graph (or at least embeddings of\n graphs with the same number of qubits).\n\n INPUTS:\n old (tup... |
Please provide a description of the function:def _find_evil(self):
M, N, L = self.M, self.N, self.L
proc = self._proc0
evil = []
cells = [(x, y) for x in range(M) for y in range(N)]
spots = [(u, v) for u in range(L) for v in range(L)]
for x, y in cells:
... | [
"A utility function that computes a list of missing couplers which\n should connect two working qubits in the same cell. The presence\n of (a nonconstant number of) these breaks the polynomial-time\n claim for our algorithm. Note: we're only actually hurt by missing\n intercell coupler... |
Please provide a description of the function:def largestNativeClique(self, max_chain_length=None):
def f(x):
return x.largestNativeClique(max_chain_length=max_chain_length)
objective = self._objective_bestscore
return self._translate(self._map_to_processors(f, objective)) | [
"Returns the largest native clique embedding we can find on the\n processor, with the shortest chainlength possible (for that clique\n size). If possible, returns a uniform choice among all largest\n cliques.\n\n INPUTS:\n max_chain_length (int): longest chain length to consi... |
Please provide a description of the function:def nativeCliqueEmbed(self, width):
def f(x):
return x.nativeCliqueEmbed(width)
objective = self._objective_bestscore
return self._translate(self._map_to_processors(f, objective)) | [
"Compute a maximum-sized native clique embedding in an induced\n subgraph of chimera with chainsize ``width+1``. If possible,\n returns a uniform choice among all largest cliques.\n\n INPUTS:\n width: width of the squares to search, also `chainlength-1`\n\n OUTPUT:\n ... |
Please provide a description of the function:def largestNativeBiClique(self, chain_imbalance=0, max_chain_length=None):
def f(x):
return x.largestNativeBiClique(chain_imbalance=chain_imbalance,
max_chain_length=max_chain_length)
objective =... | [
"Returns a native embedding for the complete bipartite graph :math:`K_{n,m}`\n for `n <= m`; where `n` is as large as possible and `m` is as large as\n possible subject to `n`. The native embedding of a complete bipartite\n graph is a set of horizontally-aligned qubits connected in lines\n ... |
Please provide a description of the function:def _translate(self, embedding):
"Translates an embedding back to linear coordinates if necessary."
if embedding is None:
return None
if not self._linear:
return embedding
return [_bulk_to_linear(self.M, self.N, self.L,... | [] |
Please provide a description of the function:def _validate_chain_strength(sampler, chain_strength):
properties = sampler.properties
if 'extended_j_range' in properties:
max_chain_strength = - min(properties['extended_j_range'])
elif 'j_range' in properties:
max_chain_strength = - min(p... | [
"Validate the provided chain strength, checking J-ranges of the sampler's children.\n\n Args:\n chain_strength (float) The provided chain strength. Use None to use J-range.\n\n Returns (float):\n A valid chain strength, either provided or based on available J-range. Positive finite float.\n\n ... |
Please provide a description of the function:def sample(self, bqm, apply_flux_bias_offsets=True, **kwargs):
child = self.child
if apply_flux_bias_offsets:
if self.flux_biases is not None:
kwargs[FLUX_BIAS_KWARG] = self.flux_biases
return child.sample(bqm, *... | [
"Sample from the given Ising model.\n\n Args:\n\n h (list/dict):\n Linear biases of the Ising model. If a list, the list's indices\n are used as variable labels.\n\n J (dict of (int, int):float):\n Quadratic biases of the Ising model.\n\n ... |
Please provide a description of the function:def get_flux_biases(sampler, embedding, chain_strength, num_reads=1000, max_age=3600):
if not isinstance(sampler, dimod.Sampler):
raise TypeError("input sampler should be DWaveSampler")
# try to read the chip_id, otherwise get the name
system_name ... | [
"Get the flux bias offsets for sampler and embedding.\n\n Args:\n sampler (:obj:`.DWaveSampler`):\n A D-Wave sampler.\n\n embedding (dict[hashable, iterable]):\n Mapping from a source graph to the specified sampler’s graph (the target graph). The\n keys of embedding... |
Please provide a description of the function:def find_clique_embedding(k, m, n=None, t=None, target_edges=None):
import random
_, nodes = k
m, n, t, target_edges = _chimera_input(m, n, t, target_edges)
# Special cases to return optimal embeddings for small k. The general clique embedder uses ch... | [
"Find an embedding for a clique in a Chimera graph.\n\n Given a target :term:`Chimera` graph size, and a clique (fully connect graph),\n attempts to find an embedding.\n\n Args:\n k (int/iterable):\n Clique to embed. If k is an integer, generates an embedding for a clique of size k\n ... |
Please provide a description of the function:def find_biclique_embedding(a, b, m, n=None, t=None, target_edges=None):
_, anodes = a
_, bnodes = b
m, n, t, target_edges = _chimera_input(m, n, t, target_edges)
embedding = processor(target_edges, M=m, N=n, L=t).tightestNativeBiClique(len(anodes), len... | [
"Find an embedding for a biclique in a Chimera graph.\n\n Given a target :term:`Chimera` graph size, and a biclique (a bipartite graph where every\n vertex in a set in connected to all vertices in the other set), attempts to find an embedding.\n\n Args:\n a (int/iterable):\n Left shore of... |
Please provide a description of the function:def find_grid_embedding(dim, m, n=None, t=4):
m, n, t, target_edges = _chimera_input(m, n, t, None)
indexer = dnx.generators.chimera.chimera_coordinates(m, n, t)
dim = list(dim)
num_dim = len(dim)
if num_dim == 1:
def _key(row, col, aisle):... | [
"Find an embedding for a grid in a Chimera graph.\n\n Given a target :term:`Chimera` graph size, and grid dimensions, attempts to find an embedding.\n\n Args:\n dim (iterable[int]):\n Sizes of each grid dimension. Length can be between 1 and 3.\n\n m (int):\n Number of rows... |
Please provide a description of the function:def cache_file(app_name=APPNAME, app_author=APPAUTHOR, filename=DATABASENAME):
user_data_dir = homebase.user_data_dir(app_name=app_name, app_author=app_author, create=True)
return os.path.join(user_data_dir, filename) | [
"Returns the filename (including path) for the data cache.\n\n The path will depend on the operating system, certain environmental\n variables and whether it is being run inside a virtual environment.\n See `homebase <https://github.com/dwavesystems/homebase>`_.\n\n Args:\n app_name (str, optiona... |
Please provide a description of the function:def _restore_isolated(sampleset, bqm, isolated):
samples = sampleset.record.sample
variables = sampleset.variables
new_samples = np.empty((len(sampleset), len(isolated)), dtype=samples.dtype)
# we don't let the isolated variables interact with each ot... | [
"Return samples-like by adding isolated variables into sampleset in a\n way that minimizes the energy (relative to the other non-isolated variables).\n "
] |
Please provide a description of the function:def _restore_isolated_higherorder(sampleset, poly, isolated):
samples = sampleset.record.sample
variables = sampleset.variables
new_samples = np.empty((len(sampleset), len(isolated)), dtype=samples.dtype)
# we don't let the isolated variables interact... | [
"Return samples-like by adding isolated variables into sampleset in a\n way that minimizes the energy (relative to the other non-isolated variables).\n\n Isolated should be ordered.\n "
] |
Please provide a description of the function:def sample(self, bqm, **parameters):
child = self.child
cutoff = self._cutoff
cutoff_vartype = self._cutoff_vartype
comp = self._comparison
if cutoff_vartype is dimod.SPIN:
original = bqm.spin
else:
... | [
"Cutoff and sample from the provided binary quadratic model.\n\n Removes interactions smaller than a given cutoff. Isolated\n variables (after the cutoff) are also removed.\n\n Note that if the problem had isolated variables before the cutoff, they\n will also be affected.\n\n Arg... |
Please provide a description of the function:def sample_poly(self, poly, **kwargs):
child = self.child
cutoff = self._cutoff
cutoff_vartype = self._cutoff_vartype
comp = self._comparison
if cutoff_vartype is dimod.SPIN:
original = poly.to_spin(copy=False)
... | [
"Cutoff and sample from the provided binary polynomial.\n\n Removes interactions smaller than a given cutoff. Isolated\n variables (after the cutoff) are also removed.\n\n Note that if the problem had isolated variables before the cutoff, they\n will also be affected.\n\n Args:\n ... |
Please provide a description of the function:def diagnose_embedding(emb, source, target):
if not hasattr(source, 'edges'):
source = nx.Graph(source)
if not hasattr(target, 'edges'):
target = nx.Graph(target)
label = {}
embedded = set()
for x in source:
try:
... | [
"A detailed diagnostic for minor embeddings.\n\n This diagnostic produces a generator, which lists all issues with `emb`. The errors\n are yielded in the form\n\n ExceptionClass, arg1, arg2,...\n\n where the arguments following the class are used to construct the exception object.\n User-friendly... |
Please provide a description of the function:def is_valid_embedding(emb, source, target):
for _ in diagnose_embedding(emb, source, target):
return False
return True | [
"A simple (bool) diagnostic for minor embeddings.\n\n See :func:`diagnose_embedding` for a more detailed diagnostic / more information.\n\n Args:\n emb (dict): a dictionary mapping source nodes to arrays of target nodes\n source (graph or edgelist): the graph to be embedded\n target (grap... |
Please provide a description of the function:def verify_embedding(emb, source, target, ignore_errors=()):
for error in diagnose_embedding(emb, source, target):
eclass = error[0]
if eclass not in ignore_errors:
raise eclass(*error[1:])
return True | [
"A simple (exception-raising) diagnostic for minor embeddings.\n\n See :func:`diagnose_embedding` for a more detailed diagnostic / more information.\n\n Args:\n emb (dict): a dictionary mapping source nodes to arrays of target nodes\n source (graph or edgelist): the graph to be embedded\n ... |
Please provide a description of the function:def resolve_object(self, object_arg_name, resolver):
def decorator(func_or_class):
if isinstance(func_or_class, type):
# Handle Resource classes decoration
# pylint: disable=protected-access
func_or... | [
"\n A helper decorator to resolve object instance from arguments (e.g. identity).\n\n Example:\n >>> @namespace.route('/<int:user_id>')\n ... class MyResource(Resource):\n ... @namespace.resolve_object(\n ... object_arg_name='user',\n ... resolver=la... |
Please provide a description of the function:def model(self, name=None, model=None, mask=None, **kwargs):
if isinstance(model, (flask_marshmallow.Schema, flask_marshmallow.base_fields.FieldABC)):
if not name:
name = model.__class__.__name__
api_model = Model(name... | [
"\n Model registration decorator.\n "
] |
Please provide a description of the function:def parameters(self, parameters, locations=None):
def decorator(func):
if locations is None and parameters.many:
_locations = ('json', )
else:
_locations = locations
if _locations is not Non... | [
"\n Endpoint parameters registration decorator.\n "
] |
Please provide a description of the function:def response(self, model=None, code=HTTPStatus.OK, description=None, **kwargs):
code = HTTPStatus(code)
if code is HTTPStatus.NO_CONTENT:
assert model is None
if model is None and code not in {HTTPStatus.ACCEPTED, HTTPStatus.NO_CO... | [
"\n Endpoint response OpenAPI documentation decorator.\n\n It automatically documents HTTPError%(code)d responses with relevant\n schemas.\n\n Arguments:\n model (flask_marshmallow.Schema) - it can be a class or an instance\n of the class, which will be used for... |
Please provide a description of the function:def _apply_decorator_to_methods(cls, decorator):
for method in cls.methods:
method_name = method.lower()
decorated_method_func = decorator(getattr(cls, method_name))
setattr(cls, method_name, decorated_method_func) | [
"\n This helper can apply a given decorator to all methods on the current\n Resource.\n\n NOTE: In contrast to ``Resource.method_decorators``, which has a\n similar use-case, this method applies decorators directly and override\n methods in-place, while the decorators listed in\n ... |
Please provide a description of the function:def options(self, *args, **kwargs):
# This is a generic implementation of OPTIONS method for resources.
# This method checks every permissions provided as decorators for other
# methods to provide information about what methods `current_user`... | [
"\n Check which methods are allowed.\n\n Use this method if you need to know what operations are allowed to be\n performed on this endpoint, e.g. to decide wether to display a button\n in your UI.\n\n The list of allowed methods is provided in `Allow` response header.\n "
] |
Please provide a description of the function:def validate_patch_structure(self, data):
if data['op'] not in self.NO_VALUE_OPERATIONS and 'value' not in data:
raise ValidationError('value is required')
if 'path' not in data:
raise ValidationError('Path is required and mu... | [
"\n Common validation of PATCH structure\n\n Provide check that 'value' present in all operations expect it.\n\n Provide check if 'path' is present. 'path' can be absent if provided\n without '/' at the start. Supposed that if 'path' is present than it\n is prepended with '/'.\n ... |
Please provide a description of the function:def perform_patch(cls, operations, obj, state=None):
if state is None:
state = {}
for operation in operations:
if not cls._process_patch_operation(operation, obj=obj, state=state):
log.info(
... | [
"\n Performs all necessary operations by calling class methods with\n corresponding names.\n "
] |
Please provide a description of the function:def _process_patch_operation(cls, operation, obj, state):
field_operaion = operation['op']
if field_operaion == cls.OP_REPLACE:
return cls.replace(obj, operation['field_name'], operation['value'], state=state)
elif field_operaio... | [
"\n Args:\n operation (dict): one patch operation in RFC 6902 format.\n obj (object): an instance which is needed to be patched.\n state (dict): inter-operations state storage\n\n Returns:\n processing_status (bool): True if operation was handled, otherwise ... |
Please provide a description of the function:def replace(cls, obj, field, value, state):
if not hasattr(obj, field):
raise ValidationError("Field '%s' does not exist, so it cannot be patched" % field)
setattr(obj, field, value)
return True | [
"\n This is method for replace operation. It is separated to provide a\n possibility to easily override it in your Parameters.\n\n Args:\n obj (object): an instance to change.\n field (str): field name\n value (str): new value\n state (dict): inter-op... |
Please provide a description of the function:def get_identities(self, item):
# All identities are in the post stream
# The first post is the question. Next replies
posts = item['data']['post_stream']['posts']
for post in posts:
user = self.get_sh_identity(post)
... | [
" Return the identities from an item "
] |
Please provide a description of the function:def __related_categories(self, category_id):
related = []
for cat in self.categories_tree:
if category_id in self.categories_tree[cat]:
related.append(self.categories[cat])
return related | [
" Get all related categories to a given one "
] |
Please provide a description of the function:def __show_categories_tree(self):
for cat in self.categories_tree:
print("%s (%i)" % (self.categories[cat], cat))
for subcat in self.categories_tree[cat]:
print("-> %s (%i)" % (self.categories[subcat], subcat)) | [
" Show the category tree: list of categories and its subcategories "
] |
Please provide a description of the function:def fetch_track_items(upstream_file_url, data_source):
track_uris = []
req = requests_ses.get(upstream_file_url)
try:
req.raise_for_status()
except requests.exceptions.HTTPError as ex:
logger.warning("Can't get gerrit reviews from %s", u... | [
" The file format is:\n\n # Upstream contributions, bitergia will crawl this and extract the relevant information\n # system is one of Gerrit, Bugzilla, Launchpad (insert more)\n ---\n -\n url: https://review.openstack.org/169836\n system: Gerrit\n "
] |
Please provide a description of the function:def _create_projects_file(project_name, data_source, items):
repositories = []
for item in items:
if item['origin'] not in repositories:
repositories.append(item['origin'])
projects = {
project_name: {
data_source: re... | [
" Create a projects file from the items origin data "
] |
Please provide a description of the function:def __convert_booleans(self, eitem):
for field in eitem.keys():
if isinstance(eitem[field], bool):
if eitem[field]:
eitem[field] = 1
else:
eitem[field] = 0
return ei... | [
" Convert True/False to 1/0 for better kibana processing "
] |
Please provide a description of the function:def enrich_items(self, ocean_backend, events=False):
max_items = self.elastic.max_items_bulk
current = 0
total = 0
bulk_json = ""
items = ocean_backend.fetch()
images_items = {}
url = self.elastic.index_url ... | [
" A custom enrich items is needed because apart from the enriched\n events from raw items, a image item with the last data for an image\n must be created "
] |
Please provide a description of the function:def get_params_parser():
parser = argparse.ArgumentParser()
ElasticOcean.add_params(parser)
parser.add_argument('-g', '--debug', dest='debug', action='store_true')
parser.add_argument('-t', '--token', dest='token', help="GitHub token")
parser.add_... | [
"Parse command line arguments"
] |
Please provide a description of the function:def get_owner_repos_url(owner, token):
url_org = GITHUB_API_URL + "/orgs/" + owner + "/repos"
url_user = GITHUB_API_URL + "/users/" + owner + "/repos"
url_owner = url_org # Use org by default
try:
r = requests.get(url_org,
... | [
" The owner could be a org or a user.\n It waits if need to have rate limit.\n Also it fixes a djando issue changing - with _\n "
] |
Please provide a description of the function:def get_repositores(owner_url, token, nrepos):
all_repos = []
url = owner_url
while True:
logging.debug("Getting repos from: %s" % (url))
try:
r = requests.get(url,
params=get_payload(),
... | [
" owner could be an org or and user "
] |
Please provide a description of the function:def create_redirect_web_page(web_dir, org_name, kibana_url):
html_redirect =
html_redirect += \
% kibana_url
html_redirect +=
html_redirect +=
html_redirect += \
% org_name
html_redirect += \
... | [
" Create HTML pages with the org name that redirect to\n the Kibana dashboard filtered for this org ",
"\n <html>\n <head>\n ",
"<meta http-equiv=\"refresh\" content=\"0; URL=%s/app/kibana",
"#/dashboard/Overview?_g=(filters:!(('$state':",
"(store:globalState),meta:(alias:!n,disabled:!f,... |
Please provide a description of the function:def notify_contact(mail, owner, graas_url, repos, first_repo=False):
footer =
twitter_txt = "Check Cauldron.io dashboard for %s at %s/dashboards/%s" % (owner, graas_url, owner)
twitter_url = "https://twitter.com/intent/tweet?text=" + quote_plus(twitter_tx... | [
" Send an email to the contact with the details to access\n the Kibana dashboard ",
"\n--\nBitergia Cauldron Team\nhttp://bitergia.com\n ",
"\nFirst repository has been analyzed and it's already in the Cauldron. Be patient, we have just started, step by step.\n\nWe will notify you when everything is r... |
Please provide a description of the function:def publish_twitter(twitter_contact, owner):
dashboard_url = CAULDRON_DASH_URL + "/%s" % (owner)
tweet = "@%s your http://cauldron.io dashboard for #%s at GitHub is ready: %s. Check it out! #oscon" \
% (twitter_contact, owner, dashboard_url)
status =... | [
" Publish in twitter the dashboard "
] |
Please provide a description of the function:def get_identities(self, item):
user = self.get_sh_identity(item, self.get_field_author())
yield user | [
"Return the identities from an item"
] |
Please provide a description of the function:def get_identities(self, item):
for rol in self.roles:
if rol in item['data']:
yield self.get_sh_identity(item["data"][rol]) | [
" Return the identities from an item "
] |
Please provide a description of the function:def get_identities(self, item):
item = item['data']
for identity in self.issue_roles:
if item[identity]:
user = self.get_sh_identity(item[identity])
if user:
yield user | [
" Return the identities from an item "
] |
Please provide a description of the function:def get_perceval_params_from_url(cls, urls):
params = []
dparam = cls.get_arthur_params_from_url(urls)
params.append(dparam["url"])
return params | [
" Get the perceval params given the URLs for the data source "
] |
Please provide a description of the function:def get_identities(self, item):
item = item['data']
for identity in ['creator']:
# Todo: questions has also involved and solved_by
if identity in item and item[identity]:
user = self.get_sh_identity(item[iden... | [
" Return the identities from an item "
] |
Please provide a description of the function:def kafka_kip(enrich):
def extract_vote_and_binding(body):
vote = 0
binding = 0 # by default the votes are binding for +1
nlines = 0
for line in body.split("\n"):
if nlines > MAX_LINES_FOR_VOTE:
... | [
" Kafka Improvement Proposals process study ",
" Extracts the vote and binding for a KIP process included in message body ",
" Extracts a KIP number from an email subject ",
" Compute the result of a votation using lazy consensus\n which requires 3 binding +1 votes and no binding vetoes.\n "... |
Please provide a description of the function:def add_identity(cls, db, identity, backend):
uuid = None
try:
uuid = api.add_identity(db, backend, identity['email'],
identity['name'], identity['username'])
logger.debug("New sortinghat ... | [
" Load and identity list from backend in Sorting Hat "
] |
Please provide a description of the function:def add_identities(cls, db, identities, backend):
logger.info("Adding the identities to SortingHat")
total = 0
for identity in identities:
try:
cls.add_identity(db, identity, backend)
total += 1
... | [
" Load identities list from backend in Sorting Hat "
] |
Please provide a description of the function:def remove_identity(cls, sh_db, ident_id):
success = False
try:
api.delete_identity(sh_db, ident_id)
logger.debug("Identity %s deleted", ident_id)
success = True
except Exception as e:
logger.de... | [
"Delete an identity from SortingHat.\n\n :param sh_db: SortingHat database\n :param ident_id: identity identifier\n "
] |
Please provide a description of the function:def remove_unique_identity(cls, sh_db, uuid):
success = False
try:
api.delete_unique_identity(sh_db, uuid)
logger.debug("Unique identity %s deleted", uuid)
success = True
except Exception as e:
... | [
"Delete a unique identity from SortingHat.\n\n :param sh_db: SortingHat database\n :param uuid: Unique identity identifier\n "
] |
Please provide a description of the function:def unique_identities(cls, sh_db):
try:
for unique_identity in api.unique_identities(sh_db):
yield unique_identity
except Exception as e:
logger.debug("Unique identities not returned from SortingHat due to %s",... | [
"List the unique identities available in SortingHat.\n\n :param sh_db: SortingHat database\n "
] |
Please provide a description of the function:def get_identities(self, item):
data = item['data']
if 'assigned_to' in data:
user = self.get_sh_identity(data, 'assigned_to')
yield user
author = self.get_sh_identity(data, 'author')
yield author | [
" Return the identities from an item "
] |
Please provide a description of the function:def get_identities(self, item):
# question
user = self.get_sh_identity(item, self.get_field_author())
yield user
# answers
if 'answers' in item['data']:
for answer in item['data']['answers']:
# av... | [
" Return the identities from an item "
] |
Please provide a description of the function:def get_identities(self, item):
user = self.get_sh_identity(item, self.get_field_author())
yield user
# Get the identities from the releases
for release in item['data']['releases']:
user = self.get_sh_identity(release['m... | [
" Return the identities from an item "
] |
Please provide a description of the function:def get_rich_events(self, item):
module = item['data']
if not item['data']['releases']:
return []
for release in item['data']['releases']:
event = self.get_rich_item(item)
# Update specific fields for this... | [
"\n Get the enriched events related to a module\n "
] |
Please provide a description of the function:def _connect(self):
try:
db = pymysql.connect(user=self.user, passwd=self.passwd,
host=self.host, port=self.port,
db=self.shdb, use_unicode=True)
return db, db.cursor(... | [
"Connect to the MySQL database.\n "
] |
Please provide a description of the function:def execute(self, query):
# sql = query.format(scm_db = self.scmdb,
# sh_db = self.shdb,
# prj_db = self.prjdb)
results = int(self.cursor.execute(query))
if results > 0:
result... | [
"Execute an SQL query with the corresponding database.\n The query can be \"templated\" with {scm_db} and {sh_db}.\n "
] |
Please provide a description of the function:def feed_arthur():
logger.info("Collecting items from redis queue")
db_url = 'redis://localhost/8'
conn = redis.StrictRedis.from_url(db_url)
logger.debug("Redis connection stablished with %s.", db_url)
# Get and remove queued items in an atomic t... | [
" Feed Ocean with backend data collected from arthur redis queue"
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.