signature
stringlengths
8
3.44k
body
stringlengths
0
1.41M
docstring
stringlengths
1
122k
id
stringlengths
5
17
@staticmethod<EOL><INDENT>def _extract_resources(elem):<DEDENT>
resources = collections.defaultdict(list)<EOL>for child in itertools.islice(elem.iter(), <NUM_LIT:1>, None):<EOL><INDENT>try:<EOL><INDENT>basename = child.tag.split('<STR_LIT:}>', <NUM_LIT:1>)[-<NUM_LIT:1>]<EOL>if child.text is not None:<EOL><INDENT>child.text = child.text.strip()<EOL><DEDENT>if child.text:<EOL><INDENT...
Extract the children of an element as a key/value mapping.
f14321:c0:m5
@classmethod<EOL><INDENT>def _iter_rawterms(cls, tree):<DEDENT>
for elem in tree.iterfind(OWL_CLASS):<EOL><INDENT>if RDF_ABOUT not in elem.keys(): <EOL><INDENT>continue <EOL><DEDENT>rawterm = cls._extract_resources(elem)<EOL>rawterm['<STR_LIT:id>'] = cls._get_id_from_url(elem.get(RDF_ABOUT))<EOL>yield rawterm<EOL><DEDENT>
Iterate through the raw terms (Classes) in the ontology.
f14321:c0:m6
@staticmethod<EOL><INDENT>def _extract_obo_synonyms(rawterm):<DEDENT>
synonyms = set()<EOL>keys = set(owl_synonyms).intersection(rawterm.keys())<EOL>for k in keys:<EOL><INDENT>for s in rawterm[k]:<EOL><INDENT>synonyms.add(Synonym(s, owl_synonyms[k]))<EOL><DEDENT><DEDENT>return synonyms<EOL>
Extract the synonyms defined in the rawterm.
f14321:c0:m7
@classmethod<EOL><INDENT>def _extract_obo_relation(cls, rawterm):<DEDENT>
relations = {}<EOL>if '<STR_LIT>' in rawterm:<EOL><INDENT>relations[Relationship('<STR_LIT>')] = l = []<EOL>l.extend(map(cls._get_id_from_url, rawterm.pop('<STR_LIT>')))<EOL><DEDENT>return relations<EOL>
Extract the relationships defined in the rawterm.
f14321:c0:m8
@staticmethod<EOL><INDENT>def _relabel_to_obo(d):<DEDENT>
return {<EOL>owl_to_obo.get(old_k, old_k): old_v<EOL>for old_k, old_v in six.iteritems(d)<EOL>}<EOL>
Change the keys of ``d`` to use Obo labels.
f14321:c0:m9
def distance(p0, p1, deg=True, r=r_earth_mean):
single, (p0, p1) = _to_arrays((p0, <NUM_LIT:2>), (p1, <NUM_LIT:2>))<EOL>if deg:<EOL><INDENT>p0 = np.radians(p0)<EOL>p1 = np.radians(p1)<EOL><DEDENT>lon0, lat0 = p0[:,<NUM_LIT:0>], p0[:,<NUM_LIT:1>]<EOL>lon1, lat1 = p1[:,<NUM_LIT:0>], p1[:,<NUM_LIT:1>]<EOL>h_dlat = sin((lat1 - lat0) / <NUM_LIT>) ** <NUM_LIT:2><EOL>h_dlo...
Return the distance between two points on the surface of the Earth. Parameters ---------- p0 : point-like (or array of point-like) [longitude, latitude] objects p1 : point-like (or array of point-like) [longitude, latitude] objects deg : bool, optional (default True) indicates if p0 and p1 are specified in degrees...
f14329:m1
def course(p0, p1, deg=True, bearing=False):
single, (p0, p1) = _to_arrays((p0, <NUM_LIT:2>), (p1, <NUM_LIT:2>))<EOL>if deg:<EOL><INDENT>p0 = np.radians(p0)<EOL>p1 = np.radians(p1)<EOL><DEDENT>lon0, lat0 = p0[:,<NUM_LIT:0>], p0[:,<NUM_LIT:1>]<EOL>lon1, lat1 = p1[:,<NUM_LIT:0>], p1[:,<NUM_LIT:1>]<EOL>dlon = lon1 - lon0<EOL>a = sin(dlon) * cos(lat1)<EOL>b = cos(lat...
Compute the initial bearing along the great circle from p0 to p1 NB: The angle returned by course() is not the traditional definition of bearing. It is definted such that 0 degrees to due East increasing counter-clockwise such that 90 degrees is due North. To obtain the bearing (0 degrees is due North increasing clock...
f14329:m2
def propagate(p0, angle, d, deg=True, bearing=False, r=r_earth_mean):
single, (p0, angle, d) = _to_arrays((p0, <NUM_LIT:2>), (angle, <NUM_LIT:1>), (d, <NUM_LIT:1>))<EOL>if deg:<EOL><INDENT>p0 = np.radians(p0)<EOL>angle = np.radians(angle)<EOL><DEDENT>if not bearing:<EOL><INDENT>angle = np.pi / <NUM_LIT> - angle<EOL><DEDENT>lon0, lat0 = p0[:,<NUM_LIT:0>], p0[:,<NUM_LIT:1>]<EOL>angd = d / ...
Given an initial point and angle, move distance d along the surface Parameters ---------- p0 : point-like (or array of point-like) [lon, lat] objects angle : float (or array of float) bearing. Note that by default, 0 degrees is due East increasing clockwise so that 90 degrees is due North. See the bearing fla...
f14329:m3
def dynamic_load(name):
pieces = name.split('<STR_LIT:.>')<EOL>item = pieces[-<NUM_LIT:1>]<EOL>mod_name = '<STR_LIT:.>'.join(pieces[:-<NUM_LIT:1>])<EOL>mod = __import__(mod_name, globals(), locals(), [item])<EOL>return getattr(mod, item)<EOL>
Equivalent of "from X import Y" statement using dot notation to specify what to import and return. For example, foo.bar.thing returns the item "thing" in the module "foo.bar
f14332:m0
def pprint(data):
print(json.dumps(data, sort_keys=True, indent=<NUM_LIT:4>, separators=('<STR_LIT:U+002C>', '<STR_LIT>')))<EOL>
Alternative to `pprint.PrettyPrinter()` that uses `json.dumps()` for sorting and displaying data. :param data: item to print to STDOUT. The item must be json serializable!
f14332:m2
def rows_to_columns(matrix):
num_rows = len(matrix)<EOL>num_cols = len(matrix[<NUM_LIT:0>])<EOL>data = []<EOL>for i in range(<NUM_LIT:0>, num_cols):<EOL><INDENT>data.append([matrix[j][i] for j in range(<NUM_LIT:0>, num_rows)])<EOL><DEDENT>return data<EOL>
Takes a two dimensional array and returns an new one where rows in the first become columns in the second.
f14332:m3
def list_to_rows(src, size):
row = []<EOL>for item in src:<EOL><INDENT>row.append(item)<EOL>if len(row) == size:<EOL><INDENT>yield row<EOL>row = []<EOL><DEDENT><DEDENT>if row:<EOL><INDENT>yield row<EOL><DEDENT>
A generator that takes a enumerable item and returns a series of slices. Useful for turning a list into a series of rows. >>> list(list_to_rows([1, 2, 3, 4, 5, 6, 7], 3)) [[1, 2, 3], [4, 5, 6], [7, ]]
f14332:m4
def head_tail_middle(src):
if len(src) == <NUM_LIT:0>:<EOL><INDENT>return None, [], None<EOL><DEDENT>if len(src) == <NUM_LIT:1>:<EOL><INDENT>return src[<NUM_LIT:0>], [], None<EOL><DEDENT>if len(src) == <NUM_LIT:2>:<EOL><INDENT>return src[<NUM_LIT:0>], [], src[<NUM_LIT:1>]<EOL><DEDENT>return src[<NUM_LIT:0>], src[<NUM_LIT:1>:-<NUM_LIT:1>], src[-<...
Returns a tuple consisting of the head of a enumerable, the middle as a list and the tail of the enumerable. If the enumerable is 1 item, the middle will be empty and the tail will be None. >>> head_tail_middle([1, 2, 3, 4]) 1, [2, 3], 4
f14332:m5
def parse_link(html):
parser = AnchorParser()<EOL>parser.feed(html)<EOL>return parser.ParsedLink(parser.url, parser.text)<EOL>
Parses an HTML anchor tag, returning the href and content text. Any content before or after the anchor tag pair is ignored. :param html: Snippet of html to parse :returns: namedtuple('ParsedLink', ['url', 'text']) Example: .. code-block:: python >>> parse_link('things <a...
f14332:m6
def getArcs(domains, constraints):
arcs = {}<EOL>for x in constraints:<EOL><INDENT>constraint, variables = x<EOL>if len(variables) == <NUM_LIT:2>:<EOL><INDENT>variable1, variable2 = variables<EOL>arcs.setdefault(variable1, {}).setdefault(variable2, []).append(x)<EOL>arcs.setdefault(variable2, {}).setdefault(variable1, []).append(x)<EOL><DEDENT><DEDENT>r...
Return a dictionary mapping pairs (arcs) of constrained variables @attention: Currently unused.
f14355:m0
def doArc8(arcs, domains, assignments):
check = dict.fromkeys(domains, True)<EOL>while check:<EOL><INDENT>variable, _ = check.popitem()<EOL>if variable not in arcs or variable in assignments:<EOL><INDENT>continue<EOL><DEDENT>domain = domains[variable]<EOL>arcsvariable = arcs[variable]<EOL>for othervariable in arcsvariable:<EOL><INDENT>arcconstraints = arcsva...
Perform the ARC-8 arc checking algorithm and prune domains @attention: Currently unused.
f14355:m1
def __init__(self, solver=None):
self._solver = solver or BacktrackingSolver()<EOL>self._constraints = []<EOL>self._variables = {}<EOL>
@param solver: Problem solver used to find solutions (default is L{BacktrackingSolver}) @type solver: instance of a L{Solver} subclass
f14355:c0:m0
def reset(self):
del self._constraints[:]<EOL>self._variables.clear()<EOL>
Reset the current problem definition Example: >>> problem = Problem() >>> problem.addVariable("a", [1, 2]) >>> problem.reset() >>> problem.getSolution() >>>
f14355:c0:m1
def setSolver(self, solver):
self._solver = solver<EOL>
Change the problem solver currently in use Example: >>> solver = BacktrackingSolver() >>> problem = Problem(solver) >>> problem.getSolver() is solver True @param solver: New problem solver @type solver: instance of a C{Solver} subclass
f14355:c0:m2
def getSolver(self):
return self._solver<EOL>
Obtain the problem solver currently in use Example: >>> solver = BacktrackingSolver() >>> problem = Problem(solver) >>> problem.getSolver() is solver True @return: Solver currently in use @rtype: instance of a L{Solver} subclass
f14355:c0:m3
def addVariable(self, variable, domain):
if variable in self._variables:<EOL><INDENT>msg = "<STR_LIT>" % repr(variable)<EOL>raise ValueError(msg)<EOL><DEDENT>if isinstance(domain, Domain):<EOL><INDENT>domain = copy.deepcopy(domain)<EOL><DEDENT>elif hasattr(domain, "<STR_LIT>"):<EOL><INDENT>domain = Domain(domain)<EOL><DEDENT>else:<EOL><INDENT>msg = "<STR_LIT>...
Add a variable to the problem Example: >>> problem = Problem() >>> problem.addVariable("a", [1, 2]) >>> problem.getSolution() in ({'a': 1}, {'a': 2}) True @param variable: Object representing a problem variable @type variable: hashable object @param domain: Set of items defining the possible values that ...
f14355:c0:m4
def addVariables(self, variables, domain):
for variable in variables:<EOL><INDENT>self.addVariable(variable, domain)<EOL><DEDENT>
Add one or more variables to the problem Example: >>> problem = Problem() >>> problem.addVariables(["a", "b"], [1, 2, 3]) >>> solutions = problem.getSolutions() >>> len(solutions) 9 >>> {'a': 3, 'b': 1} in solutions True @param variables: Any object containing a sequence of objects represeting prob...
f14355:c0:m5
def addConstraint(self, constraint, variables=None):
if not isinstance(constraint, Constraint):<EOL><INDENT>if callable(constraint):<EOL><INDENT>constraint = FunctionConstraint(constraint)<EOL><DEDENT>else:<EOL><INDENT>msg = "<STR_LIT>" "<STR_LIT>"<EOL>raise ValueError(msg)<EOL><DEDENT><DEDENT>self._constraints.append((constraint, variables))<EOL>
Add a constraint to the problem Example: >>> problem = Problem() >>> problem.addVariables(["a", "b"], [1, 2, 3]) >>> problem.addConstraint(lambda a, b: b == a+1, ["a", "b"]) >>> solutions = problem.getSolutions() >>> @param constraint: Constraint to be included in the problem @type constraint: instance a L{Constrai...
f14355:c0:m6
def getSolution(self):
domains, constraints, vconstraints = self._getArgs()<EOL>if not domains:<EOL><INDENT>return None<EOL><DEDENT>return self._solver.getSolution(domains, constraints, vconstraints)<EOL>
Find and return a solution to the problem Example: >>> problem = Problem() >>> problem.getSolution() is None True >>> problem.addVariables(["a"], [42]) >>> problem.getSolution() {'a': 42} @return: Solution for the problem @rtype: dictionary mapping variables to values
f14355:c0:m7
def getSolutions(self):
domains, constraints, vconstraints = self._getArgs()<EOL>if not domains:<EOL><INDENT>return []<EOL><DEDENT>return self._solver.getSolutions(domains, constraints, vconstraints)<EOL>
Find and return all solutions to the problem Example: >>> problem = Problem() >>> problem.getSolutions() == [] True >>> problem.addVariables(["a"], [42]) >>> problem.getSolutions() [{'a': 42}] @return: All solutions for the problem @rtype: list of dictionaries mapping variables to values
f14355:c0:m8
def getSolutionIter(self):
domains, constraints, vconstraints = self._getArgs()<EOL>if not domains:<EOL><INDENT>return iter(())<EOL><DEDENT>return self._solver.getSolutionIter(domains, constraints, vconstraints)<EOL>
Return an iterator to the solutions of the problem Example: >>> problem = Problem() >>> list(problem.getSolutionIter()) == [] True >>> problem.addVariables(["a"], [42]) >>> iter = problem.getSolutionIter() >>> next(iter) {'a': 42} >>> next(iter) Traceback (most recent call last): File "<stdin>", line 1, in ? StopIt...
f14355:c0:m9
def getSolution(self, domains, constraints, vconstraints):
msg = "<STR_LIT>" % self.__class__.__name__<EOL>raise NotImplementedError(msg)<EOL>
Return one solution for the given problem @param domains: Dictionary mapping variables to their domains @type domains: dict @param constraints: List of pairs of (constraint, variables) @type constraints: list @param vconstraints: Dictionary mapping variables to a list of constraints affecting th...
f14355:c1:m0
def getSolutions(self, domains, constraints, vconstraints):
msg = "<STR_LIT>" % self.__class__.__name__<EOL>raise NotImplementedError(msg)<EOL>
Return all solutions for the given problem @param domains: Dictionary mapping variables to domains @type domains: dict @param constraints: List of pairs of (constraint, variables) @type constraints: list @param vconstraints: Dictionary mapping variables to a list of constraints affecting the giv...
f14355:c1:m1
def getSolutionIter(self, domains, constraints, vconstraints):
msg = "<STR_LIT>" % self.__class__.__name__<EOL>raise NotImplementedError(msg)<EOL>
Return an iterator for the solutions of the given problem @param domains: Dictionary mapping variables to domains @type domains: dict @param constraints: List of pairs of (constraint, variables) @type constraints: list @param vconstraints: Dictionary mapping variables to a list of constraints af...
f14355:c1:m2
def __init__(self, forwardcheck=True):
self._forwardcheck = forwardcheck<EOL>
@param forwardcheck: If false forward checking will not be requested to constraints while looking for solutions (default is true) @type forwardcheck: bool
f14355:c2:m0
def __init__(self, forwardcheck=True):
self._forwardcheck = forwardcheck<EOL>
@param forwardcheck: If false forward checking will not be requested to constraints while looking for solutions (default is true) @type forwardcheck: bool
f14355:c3:m0
def __init__(self, steps=<NUM_LIT:1000>):
self._steps = steps<EOL>
@param steps: Maximum number of steps to perform before giving up when looking for a solution (default is 1000) @type steps: int
f14355:c4:m0
def __init__(self, name):
self.name = name<EOL>
@param name: Generic variable name for problem-specific purposes @type name: string
f14355:c5:m0
def __init__(self, set):
list.__init__(self, set)<EOL>self._hidden = []<EOL>self._states = []<EOL>
@param set: Set of values that the given variables may assume @type set: set of objects comparable by equality
f14355:c6:m0
def resetState(self):
self.extend(self._hidden)<EOL>del self._hidden[:]<EOL>del self._states[:]<EOL>
Reset to the original domain state, including all possible values
f14355:c6:m1
def pushState(self):
self._states.append(len(self))<EOL>
Save current domain state Variables hidden after that call are restored when that state is popped from the stack.
f14355:c6:m2
def popState(self):
diff = self._states.pop() - len(self)<EOL>if diff:<EOL><INDENT>self.extend(self._hidden[-diff:])<EOL>del self._hidden[-diff:]<EOL><DEDENT>
Restore domain state from the top of the stack Variables hidden since the last popped state are then available again.
f14355:c6:m3
def hideValue(self, value):
list.remove(self, value)<EOL>self._hidden.append(value)<EOL>
Hide the given value from the domain After that call the given value won't be seen as a possible value on that domain anymore. The hidden value will be restored when the previous saved state is popped. @param value: Object currently available in the domain
f14355:c6:m4
def __call__(self, variables, domains, assignments, forwardcheck=False):
return True<EOL>
Perform the constraint checking If the forwardcheck parameter is not false, besides telling if the constraint is currently broken or not, the constraint implementation may choose to hide values from the domains of unassigned variables to prevent them from being used, and thus prune the search space. @param variables:...
f14355:c7:m0
def preProcess(self, variables, domains, constraints, vconstraints):
if len(variables) == <NUM_LIT:1>:<EOL><INDENT>variable = variables[<NUM_LIT:0>]<EOL>domain = domains[variable]<EOL>for value in domain[:]:<EOL><INDENT>if not self(variables, domains, {variable: value}):<EOL><INDENT>domain.remove(value)<EOL><DEDENT><DEDENT>constraints.remove((self, variables))<EOL>vconstraints[variable]...
Preprocess variable domains This method is called before starting to look for solutions, and is used to prune domains with specific constraint logic when possible. For instance, any constraints with a single variable may be applied on all possible values and removed, since they may act on individual values even withou...
f14355:c7:m1
def forwardCheck(self, variables, domains, assignments, _unassigned=Unassigned):
unassignedvariable = _unassigned<EOL>for variable in variables:<EOL><INDENT>if variable not in assignments:<EOL><INDENT>if unassignedvariable is _unassigned:<EOL><INDENT>unassignedvariable = variable<EOL><DEDENT>else:<EOL><INDENT>break<EOL><DEDENT><DEDENT><DEDENT>else:<EOL><INDENT>if unassignedvariable is not _unassign...
Helper method for generic forward checking Currently, this method acts only when there's a single unassigned variable. @param variables: Variables affected by that constraint, in the same order provided by the user @type variables: sequence @param domains: Dictionary mapping variables to their doma...
f14355:c7:m2
def __init__(self, func, assigned=True):
self._func = func<EOL>self._assigned = assigned<EOL>
@param func: Function wrapped and queried for constraint logic @type func: callable object @param assigned: Whether the function may receive unassigned variables or not @type assigned: bool
f14355:c8:m0
def __init__(self, maxsum, multipliers=None):
self._maxsum = maxsum<EOL>self._multipliers = multipliers<EOL>
@param maxsum: Value to be considered as the maximum sum @type maxsum: number @param multipliers: If given, variable values will be multiplied by the given factors before being summed to be checked @type multipliers: sequence of numbers
f14355:c11:m0
def __init__(self, exactsum, multipliers=None):
self._exactsum = exactsum<EOL>self._multipliers = multipliers<EOL>
@param exactsum: Value to be considered as the exact sum @type exactsum: number @param multipliers: If given, variable values will be multiplied by the given factors before being summed to be checked @type multipliers: sequence of numbers
f14355:c12:m0
def __init__(self, minsum, multipliers=None):
self._minsum = minsum<EOL>self._multipliers = multipliers<EOL>
@param minsum: Value to be considered as the minimum sum @type minsum: number @param multipliers: If given, variable values will be multiplied by the given factors before being summed to be checked @type multipliers: sequence of numbers
f14355:c13:m0
def __init__(self, set):
self._set = set<EOL>
@param set: Set of allowed values @type set: set
f14355:c14:m0
def __init__(self, set):
self._set = set<EOL>
@param set: Set of disallowed values @type set: set
f14355:c15:m0
def __init__(self, set, n=<NUM_LIT:1>, exact=False):
self._set = set<EOL>self._n = n<EOL>self._exact = exact<EOL>
@param set: Set of values to be checked @type set: set @param n: Minimum number of assigned values that should be present in set (default is 1) @type n: int @param exact: Whether the number of assigned values which are present in set must be exactly C{n} @type exact: bool
f14355:c16:m0
def __init__(self, set, n=<NUM_LIT:1>, exact=False):
self._set = set<EOL>self._n = n<EOL>self._exact = exact<EOL>
@param set: Set of values to be checked @type set: set @param n: Minimum number of assigned values that should not be present in set (default is 1) @type n: int @param exact: Whether the number of assigned values which are not present in set must be exactly C{n} @type exact: bool
f14355:c17:m0
def process_docstring(app, what, name, obj, options, lines):
result = [re.sub(r'<STR_LIT>', r'<STR_LIT>',<EOL>re.sub(r'<STR_LIT>', r'<STR_LIT>',<EOL>re.sub(r'<STR_LIT>' + '<STR_LIT:|>'.join(FIELDS) + r'<STR_LIT:)>', r'<STR_LIT>',<EOL>l)))<EOL>for l in lines]<EOL>lines[:] = result[:]<EOL>
Process the docstring for a given python object. Note that the list 'lines' is changed in this function. Sphinx uses the altered content of the list.
f14357:m0
@binary_quadratic_model_sampler(<NUM_LIT:0>)<EOL>def set_default_sampler(sampler):
global _SAMPLER<EOL>_SAMPLER = sampler<EOL>
Sets a default binary quadratic model sampler. Parameters ---------- 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...
f14359:m0
def unset_default_sampler():
global _SAMPLER<EOL>_SAMPLER = None<EOL>
Resets the default sampler back to None. Examples -------- This example sets sampler0 as the default sampler, verifies the setting, then resets the default, and verifies the resetting. >>> dnx.set_default_sampler(sampler0) # doctest: +SKIP >>> print(dnx.get_default_sampler()) # doctest: +SKI...
f14359:m1
def get_default_sampler():
return _SAMPLER<EOL>
Queries the current default sampler. Examples -------- This example queries the default sampler before and after specifying a default sampler. >>> print(dnx.get_default_sampler()) # doctest: +SKIP None >>> dnx.set_default_sampler(sampler) # doctest: +SKIP >>> print(dnx.get_default_sa...
f14359:m2
def binary_quadratic_model_sampler(which_args):
@decorator<EOL>def _binary_quadratic_model_sampler(f, *args, **kw):<EOL><INDENT>if isinstance(which_args, int):<EOL><INDENT>iter_args = (which_args,)<EOL><DEDENT>else:<EOL><INDENT>iter_args = iter(which_args)<EOL><DEDENT>new_args = [arg for arg in args]<EOL>for idx in iter_args:<EOL><INDENT>sampler = args[idx]<EOL>if s...
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 -----...
f14362:m0
@binary_quadratic_model_sampler(<NUM_LIT:1>)<EOL>def maximum_clique(G, sampler=None, lagrange=<NUM_LIT>, **sampler_args):
if G is None:<EOL><INDENT>raise ValueError("<STR_LIT>")<EOL><DEDENT>complement_G = nx.complement(G)<EOL>return dnx.maximum_independent_set(complement_G, sampler, lagrange, **sampler_args)<EOL>
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 clique may also ...
f14369:m0
@binary_quadratic_model_sampler(<NUM_LIT:1>)<EOL>def clique_number(G, sampler=None, lagrange=<NUM_LIT>, **sampler_args):
return len(maximum_clique(G, sampler, lagrange, **sampler_args))<EOL>
Returns the number of vertices in the maximum clique of a graph. A maximum clique is a clique of the largest possible size in a given graph. The clique number `\omega(G)` of a graph G is the number of vertices in a maximum clique in G. The intersection number of G is the smallest number of cliques that together cover a...
f14369:m1
def is_clique(G, clique_nodes):
for x in clique_nodes:<EOL><INDENT>for y in clique_nodes:<EOL><INDENT>if x != y:<EOL><INDENT>if not(G.has_edge(x,y)):<EOL><INDENT>return False<EOL><DEDENT><DEDENT><DEDENT><DEDENT>return True<EOL>
Determines whether the given nodes forms a clique. A clique is a subset of nodes of an undirected graph such that every two distinct nodes in the clique are adjacent. Parameters ---------- G : NetworkX graph The graph on which to check the clique nodes. clique_nodes : list List ...
f14369:m2
def is_simplicial(G, n):
return all(u in G[v] for u, v in itertools.combinations(G[n], <NUM_LIT:2>))<EOL>
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 ...
f14370:m0
def is_almost_simplicial(G, n):
for w in G[n]:<EOL><INDENT>if all(u in G[v] for u, v in itertools.combinations(G[n], <NUM_LIT:2>) if u != w and v != w):<EOL><INDENT>return True<EOL><DEDENT><DEDENT>return False<EOL>
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...
f14370:m1
def minor_min_width(G):
<EOL>adj = {v: set(G[v]) for v in G}<EOL>lb = <NUM_LIT:0> <EOL>while len(adj) > <NUM_LIT:1>:<EOL><INDENT>v = min(adj, key=lambda v: len(adj[v]))<EOL>neighbors = adj[v]<EOL>if not neighbors:<EOL><INDENT>del adj[v]<EOL>continue<EOL><DEDENT>def neighborhood_degree(u):<EOL><INDENT>Gu = adj[u]<EOL>return sum(w in Gu for w ...
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...
f14370:m2
def min_fill_heuristic(G):
<EOL>adj = {v: set(G[v]) for v in G}<EOL>num_nodes = len(adj)<EOL>order = [<NUM_LIT:0>] * num_nodes<EOL>upper_bound = <NUM_LIT:0><EOL>for i in range(num_nodes):<EOL><INDENT>v = min(adj, key=lambda x: _min_fill_needed_edges(adj, x))<EOL>dv = len(adj[v])<EOL>if dv > upper_bound:<EOL><INDENT>upper_bound = dv<EOL><DEDENT>_...
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...
f14370:m3
def min_width_heuristic(G):
<EOL>adj = {v: set(G[v]) for v in G}<EOL>num_nodes = len(adj)<EOL>order = [<NUM_LIT:0>] * num_nodes<EOL>upper_bound = <NUM_LIT:0><EOL>for i in range(num_nodes):<EOL><INDENT>v = min(adj, key=lambda u: len(adj[u]) + random())<EOL>dv = len(adj[v])<EOL>if dv > upper_bound:<EOL><INDENT>upper_bound = dv<EOL><DEDENT>_elim_adj...
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...
f14370:m5
def max_cardinality_heuristic(G):
<EOL>adj = {v: set(G[v]) for v in G}<EOL>num_nodes = len(adj)<EOL>order = [<NUM_LIT:0>] * num_nodes<EOL>upper_bound = <NUM_LIT:0><EOL>labelled_neighbors = {v: <NUM_LIT:0> for v in adj}<EOL>for i in range(num_nodes):<EOL><INDENT>v = max(labelled_neighbors, key=lambda u: labelled_neighbors[u] + random())<EOL>del labelled...
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...
f14370:m6
def _elim_adj(adj, n):
neighbors = adj[n]<EOL>new_edges = set()<EOL>for u, v in itertools.combinations(neighbors, <NUM_LIT:2>):<EOL><INDENT>if v not in adj[u]:<EOL><INDENT>adj[u].add(v)<EOL>adj[v].add(u)<EOL>new_edges.add((u, v))<EOL>new_edges.add((v, u))<EOL><DEDENT><DEDENT>for v in neighbors:<EOL><INDENT>adj[v].discard(n)<EOL><DEDENT>del a...
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 ...
f14370:m7
def elimination_order_width(G, order):
<EOL>adj = {v: set(G[v]) for v in G}<EOL>treewidth = <NUM_LIT:0><EOL>for v in order:<EOL><INDENT>try:<EOL><INDENT>dv = len(adj[v])<EOL><DEDENT>except KeyError:<EOL><INDENT>raise ValueError('<STR_LIT>'.format(v))<EOL><DEDENT>if dv > treewidth:<EOL><INDENT>treewidth = dv<EOL><DEDENT>_elim_adj(adj, v)<EOL><DEDENT>if adj:<...
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 ...
f14370:m8
def treewidth_branch_and_bound(G, elimination_order=None, treewidth_upperbound=None):
<EOL>if not any(G[v] for v in G):<EOL><INDENT>return <NUM_LIT:0>, list(G)<EOL><DEDENT>x = [] <EOL>f = minor_min_width(G) <EOL>g = <NUM_LIT:0> <EOL>ub, order = min_fill_heuristic(G)<EOL>if elimination_order is not None:<EOL><INDENT>upperbound = elimination_order_width(G, elimination_order)<EOL>if upperbound <= ub:<EO...
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...
f14370:m9
def _branch_and_bound(adj, x, g, f, best_found, skipable=set(), theorem6p2=None):
<EOL>if theorem6p2 is None:<EOL><INDENT>theorem6p2 = _theorem6p2()<EOL><DEDENT>prune6p2, explored6p2, finished6p2 = theorem6p2<EOL>current6p2 = list()<EOL>prune6p4, explored6p4 = _theorem6p4()<EOL>ub, order = best_found<EOL>if len(adj) < <NUM_LIT:2>:<EOL><INDENT>if f < ub:<EOL><INDENT>return (f, x + list(adj))<EOL><DED...
Recursive branch and bound for computing treewidth of a subgraph. adj: adjacency list x: partial elimination order g: width of x so far f: lower bound on width of any elimination order starting with x best_found = ub,order: best upper bound on the treewidth found so far, and its elimination order ...
f14370:m10
def _graph_reduction(adj, x, g, f):
as_list = set()<EOL>as_nodes = {v for v in adj if len(adj[v]) <= f and is_almost_simplicial(adj, v)}<EOL>while as_nodes:<EOL><INDENT>as_list.union(as_nodes)<EOL>for n in as_nodes:<EOL><INDENT>dv = len(adj[n])<EOL>if dv > g:<EOL><INDENT>g = dv<EOL><DEDENT>if g > f:<EOL><INDENT>f = g<EOL><DEDENT>x.append(n)<EOL>_elim_adj...
we can go ahead and remove any simplicial or almost-simplicial vertices from adj.
f14370:m11
def _theorem5p4(adj, ub):
new_edges = set()<EOL>for u, v in itertools.combinations(adj, <NUM_LIT:2>):<EOL><INDENT>if u in adj[v]:<EOL><INDENT>continue<EOL><DEDENT>if len(adj[u].intersection(adj[v])) > ub:<EOL><INDENT>new_edges.add((u, v))<EOL><DEDENT><DEDENT>while new_edges:<EOL><INDENT>for u, v in new_edges:<EOL><INDENT>adj[u].add(v)<EOL>adj[v...
By Theorem 5.4, if any two vertices have ub + 1 common neighbors then we can add an edge between them.
f14370:m12
def _theorem6p1():
pruning_set = set()<EOL>def _prune(x):<EOL><INDENT>if len(x) <= <NUM_LIT:2>:<EOL><INDENT>return False<EOL><DEDENT>key = (tuple(x[:-<NUM_LIT:2>]), x[-<NUM_LIT:2>], x[-<NUM_LIT:1>])<EOL>return key in pruning_set<EOL><DEDENT>def _explored(x):<EOL><INDENT>if len(x) >= <NUM_LIT:3>:<EOL><INDENT>prunable = (tuple(x[:-<NUM_LIT...
See Theorem 6.1 in paper.
f14370:m13
def _theorem6p2():
pruning_set2 = set()<EOL>def _prune2(x, a, nbrs_a):<EOL><INDENT>frozen_nbrs_a = frozenset(nbrs_a)<EOL>for i in range(len(x)):<EOL><INDENT>key = (tuple(x[<NUM_LIT:0>:i]), a, frozen_nbrs_a)<EOL>if key in pruning_set2:<EOL><INDENT>return True<EOL><DEDENT><DEDENT>return False<EOL><DEDENT>def _explored2(x, a, nbrs_a):<EOL><...
See Theorem 6.2 in paper. Prunes (x,...,a) when (x,a) is explored and a has the same neighbour set in both graphs.
f14370:m14
def _theorem6p3():
pruning_set3 = set()<EOL>def _prune3(x, as_list, b):<EOL><INDENT>for a in as_list:<EOL><INDENT>key = (tuple(x), a, b) <EOL>if key in pruning_set3:<EOL><INDENT>return True<EOL><DEDENT><DEDENT>return False<EOL><DEDENT>def _explored3(x, a, as_list):<EOL><INDENT>for b in as_list:<EOL><INDENT>prunable = (tuple(x), a, b) <...
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)
f14370:m15
def _theorem6p4():
pruning_set4 = list()<EOL>def _prune4(edges_b):<EOL><INDENT>for edges_a in pruning_set4:<EOL><INDENT>if edges_a.issubset(edges_b):<EOL><INDENT>return True<EOL><DEDENT><DEDENT>return False<EOL><DEDENT>def _explored4(edges_a):<EOL><INDENT>pruning_set4.append(edges_a) <EOL><DEDENT>return _prune4, _explored4<EOL>
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...
f14370:m16
def powerset(iterable):
s = list(iterable)<EOL>return chain.from_iterable(combinations(s, r) for r in range(len(s) + <NUM_LIT:1>))<EOL>
powerset([1,2,3]) --> () (1,) (2,) (3,) (1,2) (1,3) (2,3) (1,2,3)
f14374:m0
def canonical_chimera_labeling(G, t=None):
adj = G.adj<EOL>if t is None:<EOL><INDENT>if hasattr(G, '<STR_LIT>'):<EOL><INDENT>num_edges = len(G.edges)<EOL><DEDENT>else:<EOL><INDENT>num_edges = len(G.quadratic)<EOL><DEDENT>t = _chimera_shore_size(adj, num_edges)<EOL><DEDENT>chimera_indices = {}<EOL>row = col = <NUM_LIT:0><EOL>root = min(adj, key=lambda v: len(adj...
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...
f14382:m0
@binary_quadratic_model_sampler(<NUM_LIT:1>)<EOL>def sample_markov_network(MN, sampler=None, fixed_variables=None,<EOL>return_sampleset=False,<EOL>**sampler_args):
bqm = markov_network_bqm(MN)<EOL>fv_sampler = dimod.FixedVariableComposite(sampler)<EOL>sampleset = fv_sampler.sample(bqm, fixed_variables=fixed_variables,<EOL>**sampler_args)<EOL>if return_sampleset:<EOL><INDENT>return sampleset<EOL><DEDENT>else:<EOL><INDENT>return list(map(dict, sampleset.samples()))<EOL><DEDENT>
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 a...
f14383:m0
def markov_network_bqm(MN):
bqm = dimod.BinaryQuadraticModel.empty(dimod.BINARY)<EOL>for v, ddict in MN.nodes(data=True, default=None):<EOL><INDENT>potential = ddict.get('<STR_LIT>', None)<EOL>if potential is None:<EOL><INDENT>continue<EOL><DEDENT>phi0 = potential[(<NUM_LIT:0>,)]<EOL>phi1 = potential[(<NUM_LIT:1>,)]<EOL>bqm.add_variable(v, phi1 -...
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.
f14383:m1
@binary_quadratic_model_sampler(<NUM_LIT:1>)<EOL>def structural_imbalance(S, sampler=None, **sampler_args):
h, J = structural_imbalance_ising(S)<EOL>response = sampler.sample_ising(h, J, **sampler_args)<EOL>sample = next(iter(response))<EOL>colors = {v: (spin + <NUM_LIT:1>) // <NUM_LIT:2> for v, spin in iteritems(sample)}<EOL>frustrated_edges = {}<EOL>for u, v, data in S.edges(data=True):<EOL><INDENT>sign = data['<STR_LIT>']...
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...
f14384:m0
def structural_imbalance_ising(S):
h = {v: <NUM_LIT:0.0> for v in S}<EOL>J = {}<EOL>for u, v, data in S.edges(data=True):<EOL><INDENT>try:<EOL><INDENT>J[(u, v)] = -<NUM_LIT:1.> * data['<STR_LIT>']<EOL><DEDENT>except KeyError:<EOL><INDENT>raise ValueError(("<STR_LIT>"<EOL>"<STR_LIT>"))<EOL><DEDENT><DEDENT>return h, J<EOL>
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,...
f14384:m1
@binary_quadratic_model_sampler(<NUM_LIT:2>)<EOL>def min_weighted_vertex_cover(G, weight=None, sampler=None, **sampler_args):
indep_nodes = set(maximum_weighted_independent_set(G, weight, sampler, **sampler_args))<EOL>return [v for v in G if v not in indep_nodes]<EOL>
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...
f14385:m0
@binary_quadratic_model_sampler(<NUM_LIT:1>)<EOL>def min_vertex_cover(G, sampler=None, **sampler_args):
return min_weighted_vertex_cover(G, None, sampler, **sampler_args)<EOL>
Returns an approximate minimum vertex cover. Defines a QUBO with ground states corresponding to a minimum 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 vertex cover ...
f14385:m1
def is_vertex_cover(G, vertex_cover):
cover = set(vertex_cover)<EOL>return all(u in cover or v in cover for u, v in G.edges)<EOL>
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...
f14385:m2
@binary_quadratic_model_sampler(<NUM_LIT:1>)<EOL>def maximum_cut(G, sampler=None, **sampler_args):
<EOL>h = {v: <NUM_LIT:0.> for v in G}<EOL>J = {(u, v): <NUM_LIT:1> for u, v in G.edges}<EOL>response = sampler.sample_ising(h, J, **sampler_args)<EOL>sample = next(iter(response))<EOL>return set(v for v in G if sample[v] >= <NUM_LIT:0>)<EOL>
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. ...
f14387:m0
def weighted_maximum_cut(G, sampler=None, **sampler_args):
<EOL>h = {v: <NUM_LIT:0.> for v in G}<EOL>try:<EOL><INDENT>J = {(u, v): G[u][v]['<STR_LIT>'] for u, v in G.edges}<EOL><DEDENT>except KeyError:<EOL><INDENT>raise DWaveNetworkXException("<STR_LIT>")<EOL><DEDENT>response = sampler.sample_ising(h, J, **sampler_args)<EOL>sample = next(iter(response))<EOL>return set(v for v ...
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 complement...
f14387:m1
@binary_quadratic_model_sampler(<NUM_LIT:2>)<EOL>def maximum_weighted_independent_set(G, weight=None, sampler=None, lagrange=<NUM_LIT>, **sampler_args):
<EOL>Q = maximum_weighted_independent_set_qubo(G, weight, lagrange)<EOL>response = sampler.sample_qubo(Q, **sampler_args)<EOL>sample = next(iter(response))<EOL>return [node for node in sample if sample[node] > <NUM_LIT:0>]<EOL>
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...
f14388:m0
@binary_quadratic_model_sampler(<NUM_LIT:1>)<EOL>def maximum_independent_set(G, sampler=None, lagrange=<NUM_LIT>, **sampler_args):
return maximum_weighted_independent_set(G, None, sampler, lagrange, **sampler_args)<EOL>
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 ...
f14388:m1
def is_independent_set(G, indep_nodes):
return len(G.subgraph(indep_nodes).edges) == <NUM_LIT:0><EOL>
Determines whether the given nodes form an independent set. An independent set is a set of nodes such that the subgraph of G induced by these nodes contains no edges. Parameters ---------- G : NetworkX graph The graph on which to check the independent set. indep_nodes : list Lis...
f14388:m2
def maximum_weighted_independent_set_qubo(G, weight=None, lagrange=<NUM_LIT>):
<EOL>if not G:<EOL><INDENT>return {}<EOL><DEDENT>cost = dict(G.nodes(data=weight, default=<NUM_LIT:1>))<EOL>scale = max(cost.values())<EOL>Q = {(node, node): min(-cost[node] / scale, <NUM_LIT:0.0>) for node in G}<EOL>Q.update({edge: lagrange for edge in G.edges})<EOL>return Q<EOL>
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...
f14388:m3
@binary_quadratic_model_sampler(<NUM_LIT:1>)<EOL>def traveling_salesman(G, sampler=None, lagrange=<NUM_LIT:2>, weight='<STR_LIT>',<EOL>**sampler_args):
<EOL>Q = traveling_salesman_qubo(G, lagrange, weight)<EOL>response = sampler.sample_qubo(Q, **sampler_args)<EOL>sample = next(iter(response))<EOL>route = []<EOL>for entry in sample:<EOL><INDENT>if sample[entry] > <NUM_LIT:0>:<EOL><INDENT>route.append(entry)<EOL><DEDENT><DEDENT>route.sort(key=lambda x: x[<NUM_LIT:1>])<E...
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 wei...
f14389:m0
def traveling_salesman_qubo(G, lagrange=<NUM_LIT:2>, weight='<STR_LIT>'):
N = G.number_of_nodes()<EOL>if N in (<NUM_LIT:1>, <NUM_LIT:2>) or len(G.edges) != N*(N-<NUM_LIT:1>)//<NUM_LIT:2>:<EOL><INDENT>msg = "<STR_LIT>"<EOL>raise ValueError(msg)<EOL><DEDENT>Q = defaultdict(float)<EOL>for node in G:<EOL><INDENT>for pos_1 in range(N):<EOL><INDENT>Q[((node, pos_1), (node, pos_1))] -= lagrange<EOL...
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...
f14389:m1
def is_hamiltonian_path(G, route):
return (len(route) == len(set(G)))<EOL>
Determines whether the given list forms a valid TSP route. A travelling salesperson route must visit each city exactly once. Parameters ---------- G : NetworkX graph The graph on which to check the route. route : list List of nodes in the order that they are visited. Return...
f14389:m2
@binary_quadratic_model_sampler(<NUM_LIT:1>)<EOL>def min_vertex_coloring(G, sampler=None, **sampler_args):
<EOL>if not nx.is_connected(G):<EOL><INDENT>coloring = {}<EOL>for subG in (G.subgraph(c).copy() for c in nx.connected_components(G)):<EOL><INDENT>sub_coloring = min_vertex_coloring(subG, sampler, **sampler_args)<EOL>coloring.update(sub_coloring)<EOL><DEDENT>return coloring<EOL><DEDENT>n_nodes = len(G) <EOL>n_edges = l...
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. ...
f14390:m0
def _minimum_coloring_qubo(x_vars, chi_lb, chi_ub, magnitude=<NUM_LIT:1.>):
<EOL>if chi_lb == chi_ub:<EOL><INDENT>return {}<EOL><DEDENT>scaling = magnitude / (chi_ub - chi_lb)<EOL>Q = {}<EOL>for v in x_vars:<EOL><INDENT>for f, color in enumerate(range(chi_lb, chi_ub)):<EOL><INDENT>idx = x_vars[v][color]<EOL>Q[(idx, idx)] = (f + <NUM_LIT:1>) * scaling<EOL><DEDENT><DEDENT>return Q<EOL>
We want to disincentivize unneeded colors. Generates the QUBO that does that.
f14390:m2
def _vertex_different_colors_qubo(G, x_vars):
Q = {}<EOL>for u, v in G.edges:<EOL><INDENT>if u not in x_vars or v not in x_vars:<EOL><INDENT>continue<EOL><DEDENT>for color in x_vars[u]:<EOL><INDENT>if color in x_vars[v]:<EOL><INDENT>Q[(x_vars[u][color], x_vars[v][color])] = <NUM_LIT:1.><EOL><DEDENT><DEDENT><DEDENT>return Q<EOL>
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.
f14390:m3
def _vertex_one_color_qubo(x_vars):
Q = {}<EOL>for v in x_vars:<EOL><INDENT>for color in x_vars[v]:<EOL><INDENT>idx = x_vars[v][color]<EOL>Q[(idx, idx)] = -<NUM_LIT:1><EOL><DEDENT>for color0, color1 in itertools.combinations(x_vars[v], <NUM_LIT:2>):<EOL><INDENT>idx0 = x_vars[v][color0]<EOL>idx1 = x_vars[v][color1]<EOL>Q[(idx0, idx1)] = <NUM_LIT:2><EOL><D...
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.
f14390:m4
def _partial_precolor(G, chi_ub):
<EOL>v = next(iter(G))<EOL>clique = [v]<EOL>for u in G[v]:<EOL><INDENT>if all(w in G[u] for w in clique):<EOL><INDENT>clique.append(u)<EOL><DEDENT><DEDENT>partial_coloring = {v: c for c, v in enumerate(clique)}<EOL>chi_lb = len(partial_coloring) <EOL>possible_colors = {v: set(range(chi_ub)) for v in G if v not in part...
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 ...
f14390:m5
def is_cycle(G):
trailing, leading = next(iter(G.edges))<EOL>start_node = trailing<EOL>n_visited = <NUM_LIT:1><EOL>while leading != start_node:<EOL><INDENT>neighbors = G[leading]<EOL>if len(neighbors) != <NUM_LIT:2>:<EOL><INDENT>return False<EOL><DEDENT>node1, node2 = neighbors<EOL>if node1 == trailing:<EOL><INDENT>trailing, leading = ...
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...
f14390:m6
def is_vertex_coloring(G, coloring):
return all(coloring[u] != coloring[v] for u, v in G.edges)<EOL>
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 ---...
f14390:m7
@binary_quadratic_model_sampler(<NUM_LIT:1>)<EOL>def maximal_matching(G, sampler=None, **sampler_args):
<EOL>delta = max(G.degree(node) for node in G)<EOL>A = <NUM_LIT:1.><EOL>if delta == <NUM_LIT:2>:<EOL><INDENT>B = <NUM_LIT><EOL><DEDENT>else:<EOL><INDENT>B = <NUM_LIT> * A / (delta - <NUM_LIT>) <EOL><DEDENT>edge_mapping = _edge_mapping(G)<EOL>Q = _maximal_matching_qubo(G, edge_mapping, magnitude=B)<EOL>Qm = _matching_q...
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...
f14391:m0
@binary_quadratic_model_sampler(<NUM_LIT:1>)<EOL>def min_maximal_matching(G, sampler=None, **sampler_args):
<EOL>delta = max(G.degree(node) for node in G)<EOL>A = <NUM_LIT:1.><EOL>if delta == <NUM_LIT:2>:<EOL><INDENT>B = <NUM_LIT><EOL><DEDENT>else:<EOL><INDENT>B = <NUM_LIT> * A / (delta - <NUM_LIT>) <EOL><DEDENT>C = <NUM_LIT> * B <EOL>edge_mapping = _edge_mapping(G)<EOL>Q = _maximal_matching_qubo(G, edge_mapping, magnitude...
Returns an approximate minimum maximal matching. Defines a QUBO with ground states corresponding to a minimum 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 a...
f14391:m1