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>resources[basename].append(child.text)<EOL><DEDENT>elif child.get(RDF_RESOURCE) is not None:<EOL><INDENT>resources[basename].append(child.get(RDF_RESOURCE))<EOL><DEDENT><DEDENT>except AttributeError:<EOL><INDENT>pass<EOL><DEDENT><DEDENT>return dict(resources)<EOL> | 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_dlon = sin((lon1 - lon0) / <NUM_LIT>) ** <NUM_LIT:2><EOL>h_angle = h_dlat + cos(lat0) * cos(lat1) * h_dlon<EOL>angle = <NUM_LIT> * arcsin(sqrt(h_angle))<EOL>d = r * angle<EOL>if single:<EOL><INDENT>d = d[<NUM_LIT:0>]<EOL><DEDENT>return d<EOL> | 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
r : float, optional (default r_earth_mean)
radius of the sphere
Returns
-------
d : float
Reference
---------
http://www.movable-type.co.uk/scripts/latlong.html - Distance
Note: Spherical earth model. By default uses radius of 6371.0 km. | 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(lat0) * sin(lat1) - sin(lat0) * cos(lat1) * cos(dlon)<EOL>if bearing:<EOL><INDENT>angle = arctan2(a, b)<EOL><DEDENT>else:<EOL><INDENT>angle = arctan2(b, a)<EOL><DEDENT>if deg:<EOL><INDENT>angle = np.degrees(angle)<EOL><DEDENT>if single:<EOL><INDENT>angle = angle[<NUM_LIT:0>]<EOL><DEDENT>return angle<EOL> | 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 clockwise so that 90 degrees is due
East), set the bearing flag input to True.
Parameters
----------
p0 : point-like (or array of point-like) [lon, lat] objects
p1 : point-like (or array of point-like) [lon, lat] objects
deg : bool, optional (default True)
indicates if p0 and p1 are specified in degrees. The returned
angle is returned in the same units as the input.
bearing : bool, optional (default False)
If True, use the classical definition of bearing where 0 degrees is
due North increasing clockwise so that and 90 degrees is due East.
Reference
---------
http://www.movable-type.co.uk/scripts/latlong.html - Bearing | 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 / r<EOL>lat1 = arcsin(sin(lat0) * cos(angd) + cos(lat0) * sin(angd) * cos(angle))<EOL>a = sin(angle) * sin(angd) * cos(lat0)<EOL>b = cos(angd) - sin(lat0) * sin(lat1)<EOL>lon1 = lon0 + arctan2(a, b)<EOL>p1 = np.column_stack([lon1, lat1])<EOL>if deg:<EOL><INDENT>p1 = np.degrees(p1)<EOL><DEDENT>if single:<EOL><INDENT>p1 = p1[<NUM_LIT:0>]<EOL><DEDENT>return p1<EOL> | 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 flag
to change the meaning of this angle
d : float (or array of float)
distance to move. The units of d should be consistent with input r
deg : bool, optional (default True)
Whether both p0 and angle are specified in degrees. The output
points will also match the value of this flag.
bearing : bool, optional (default False)
Indicates whether to interpret the input angle as the classical
definition of bearing.
r : float, optional (default r_earth_mean)
radius of the sphere
Reference
---------
http://www.movable-type.co.uk/scripts/latlong.html - Destination
Note: Spherical earth model. By default uses radius of 6371.0 km. | 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[-<NUM_LIT:1>]<EOL> | 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 href="/foo/bar.html">Foo</a> stuff')
ParsedLink('/foo/bar.html', 'Foo') | 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>return arcs<EOL> | 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 = arcsvariable[othervariable]<EOL>if othervariable in assignments:<EOL><INDENT>otherdomain = [assignments[othervariable]]<EOL><DEDENT>else:<EOL><INDENT>otherdomain = domains[othervariable]<EOL><DEDENT>if domain:<EOL><INDENT>for value in domain[:]:<EOL><INDENT>assignments[variable] = value<EOL>if otherdomain:<EOL><INDENT>for othervalue in otherdomain:<EOL><INDENT>assignments[othervariable] = othervalue<EOL>for constraint, variables in arcconstraints:<EOL><INDENT>if not constraint(<EOL>variables, domains, assignments, True<EOL>):<EOL><INDENT>break<EOL><DEDENT><DEDENT>else:<EOL><INDENT>break<EOL><DEDENT><DEDENT>else:<EOL><INDENT>domain.hideValue(value)<EOL><DEDENT>del assignments[othervariable]<EOL><DEDENT><DEDENT>del assignments[variable]<EOL><DEDENT>if not domain:<EOL><INDENT>return False<EOL><DEDENT><DEDENT><DEDENT>return True<EOL> | 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>"<EOL>raise TypeError(msg)<EOL><DEDENT>if not domain:<EOL><INDENT>raise ValueError("<STR_LIT>")<EOL><DEDENT>self._variables[variable] = domain<EOL> | 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
the given variable may assume
@type domain: list, tuple, or instance of C{Domain} | 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 problem variables
@type variables: sequence of hashable objects
@param domain: Set of items defining the possible values that
the given variables may assume
@type domain: list, tuple, or instance of C{Domain} | 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{Constraint} subclass or a
function to be wrapped by L{FunctionConstraint}
@param variables: Variables affected by the constraint (default to
all variables). Depending on the constraint type
the order may be important.
@type variables: set or sequence of variables | 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 ?
StopIteration | 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 the given variables.
@type vconstraints: dict | 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 given variables.
@type vconstraints: dict | 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 affecting the given variables.
@type vconstraints: dict | 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: Variables affected by that constraint, in the
same order provided by the user
@type variables: sequence
@param domains: Dictionary mapping variables to their domains
@type domains: dict
@param assignments: Dictionary mapping assigned variables to their
current assumed value
@type assignments: dict
@param forwardcheck: Boolean value stating whether forward checking
should be performed or not
@return: Boolean value stating if this constraint is currently
broken or not
@rtype: bool | 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].remove((self, variables))<EOL><DEDENT> | 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 without further
knowledge about other assignments.
@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 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 given variables.
@type vconstraints: dict | 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 _unassigned:<EOL><INDENT>domain = domains[unassignedvariable]<EOL>if domain:<EOL><INDENT>for value in domain[:]:<EOL><INDENT>assignments[unassignedvariable] = value<EOL>if not self(variables, domains, assignments):<EOL><INDENT>domain.hideValue(value)<EOL><DEDENT><DEDENT>del assignments[unassignedvariable]<EOL><DEDENT>if not domain:<EOL><INDENT>return False<EOL><DEDENT><DEDENT><DEDENT>return True<EOL> | 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 domains
@type domains: dict
@param assignments: Dictionary mapping assigned variables to their
current assumed value
@type assignments: dict
@return: Boolean value stating if this constraint is currently
broken or not
@rtype: bool | 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 sampler is expected to have a 'sample_qubo'
and 'sample_ising' method. A sampler is expected to return an
iterable of samples, in order of increasing energy.
Examples
--------
This example sets sampler0 as the default sampler and finds an independent
set for graph G, first using the default sampler and then overriding it by
specifying a different sampler.
>>> dnx.set_default_sampler(sampler0) # doctest: +SKIP
>>> indep_set = dnx.maximum_independent_set_dm(G) # doctest: +SKIP
>>> indep_set = dnx.maximum_independent_set_dm(G, sampler1) # doctest: +SKIP | 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: +SKIP
'sampler0'
>>> dnx.unset_default_sampler() # doctest: +SKIP
>>> print(dnx.get_default_sampler()) # doctest: +SKIP
None | 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_sampler()) # doctest: +SKIP
'sampler' | 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 sampler is None:<EOL><INDENT>default_sampler = dnx.get_default_sampler()<EOL>if default_sampler is None:<EOL><INDENT>raise dnx.DWaveNetworkXMissingSampler('<STR_LIT>')<EOL><DEDENT>new_args[idx] = default_sampler<EOL>continue<EOL><DEDENT>if not hasattr(sampler, "<STR_LIT>") or not callable(sampler.sample_qubo):<EOL><INDENT>raise TypeError("<STR_LIT>")<EOL><DEDENT>if not hasattr(sampler, "<STR_LIT>") or not callable(sampler.sample_ising):<EOL><INDENT>raise TypeError("<STR_LIT>")<EOL><DEDENT><DEDENT>return f(*new_args, **kw)<EOL><DEDENT>return _binary_quadratic_model_sampler<EOL> | Decorator to validate sampler arguments.
Parameters
----------
which_args : int or sequence of ints
Location of the sampler arguments of the input function in the form
`function_name(args, *kw)`. If more than one
sampler is allowed, can be a list of locations.
Returns
-------
_binary_quadratic_model_sampler : function
Caller function that validates the sampler format. A sampler
is expected to have `sample_qubo` and `sample_ising` methods.
Alternatively, if no sampler is provided (or sampler is None),
the sampler set by the `set_default_sampler` function is provided to
the function.
Examples
--------
Decorate functions like this::
@binary_quadratic_model_sampler(1)
def maximal_matching(G, sampler, **sampler_args):
pass
This example validates two placeholder samplers, which return a correct
response only in the case of finding an independent set on a complete graph
(where one node is always an independent set), the first valid, the second
missing a method.
>>> import networkx as nx
>>> import dwave_networkx as dnx
>>> from dwave_networkx.utils import decorators
>>> # Create two placeholder samplers
>>> class WellDefinedSampler:
... # an example sampler, only works for independent set on complete
... # graphs
... def __init__(self, name):
... self.name = name
... def sample_ising(self, h, J):
... sample = {v: -1 for v in h}
... sample[0] = 1 # set one node to true
... return [sample]
... def sample_qubo(self, Q):
... sample = {v: 0 for v in set().union(*Q)}
... sample[0] = 1 # set one node to true
... return [sample]
... def __str__(self):
... return self.name
...
>>> class IllDefinedSampler:
... # an example sampler missing a `sample_qubo` method
... def __init__(self, name):
... self.name = name
... def sample_ising(self, h, J):
... sample = {v: -1 for v in h}
... sample[0] = 1 # set one node to true
... return [sample]
... def __str__(self):
... return self.name
...
>>> sampler1 = WellDefinedSampler('sampler1')
>>> sampler2 = IllDefinedSampler('sampler2')
>>> # Define a placeholder independent-set function with the decorator
>>> @dnx.utils.binary_quadratic_model_sampler(1)
... def independent_set(G, sampler, **sampler_args):
... Q = {(node, node): -1 for node in G}
... Q.update({edge: 2 for edge in G.edges})
... response = sampler.sample_qubo(Q, **sampler_args)
... sample = next(iter(response))
... return [node for node in sample if sample[node] > 0]
...
>>> # Validate the samplers
>>> G = nx.complete_graph(5)
>>> independent_set(G, sampler1)
[0]
>>> independent_set(G, sampler2) # doctest: +SKIP
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
<ipython-input-35-670b71b268c7> in <module>()
----> 1 independent_set(G, IllDefinedSampler)
<decorator-gen-628> in independent_set(G, sampler, **sampler_args)
/usr/local/lib/python2.7/dist-packages/dwave_networkx/utils/decorators.pyc in _binary_quadratic_model_sampler(f, *args, **kw)
61
62 if not hasattr(sampler, "sample_qubo") or not callable(sampler.sample_qubo):
---> 63 raise TypeError("expected sampler to have a 'sample_qubo' method")
64 if not hasattr(sampler, "sample_ising") or not callable(sampler.sample_ising):
65 raise TypeError("expected sampler to have a 'sample_ising' method")
TypeError: expected sampler to have a 'sample_qubo' method | 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 refer
to the subgraph).A maximum clique is a clique of the largest
possible size in a given graph.
This function works by finding the maximum independent set of the compliment
graph of the given graph G which is equivalent to finding maximum clique.
It defines a QUBO with ground states corresponding
to a maximum weighted independent set and uses the sampler to sample from it.
Parameters
----------
G : NetworkX graph
The graph on which to find a maximum clique.
sampler
A binary quadratic model sampler. A sampler is a process that
samples from low energy states in models defined by an Ising
equation or a Quadratic Unconstrained Binary Optimization
Problem (QUBO). A sampler is expected to have a 'sample_qubo'
and 'sample_ising' method. A sampler is expected to return an
iterable of samples, in order of increasing energy. If no
sampler is provided, one must be provided using the
`set_default_sampler` function.
lagrange : optional (default 2)
Lagrange parameter to weight constraints (no edges within set)
versus objective (largest set possible).
sampler_args
Additional keyword parameters are passed to the sampler.
Returns
-------
clique_nodes : list
List of nodes that form a maximum clique, as
determined by the given sampler.
Notes
-----
Samplers by their nature may not return the optimal solution. This
function does not attempt to confirm the quality of the returned
sample.
References
----------
`Maximum Clique on Wikipedia <https://en.wikipedia.org/wiki/Maximum_clique(graph_theory)>`_
`Independent Set on Wikipedia <https://en.wikipedia.org/wiki/Independent_set_(graph_theory)>`_
`QUBO on Wikipedia <https://en.wikipedia.org/wiki/Quadratic_unconstrained_binary_optimization>`_
.. [AL] Lucas, A. (2014). Ising formulations of many NP problems.
Frontiers in Physics, Volume 2, Article 5. | 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 all edges of G.
This function works by finding the maximum independent set of the compliment
graph of the given graph G which is equivalent to finding maximum clique.
It defines a QUBO with ground states corresponding
to a maximum weighted independent set and uses the sampler to sample from it.
Parameters
----------
G : NetworkX graph
The graph on which to find a maximum clique.
sampler
A binary quadratic model sampler. A sampler is a process that
samples from low energy states in models defined by an Ising
equation or a Quadratic Unconstrained Binary Optimization
Problem (QUBO). A sampler is expected to have a 'sample_qubo'
and 'sample_ising' method. A sampler is expected to return an
iterable of samples, in order of increasing energy. If no
sampler is provided, one must be provided using the
`set_default_sampler` function.
lagrange : optional (default 2)
Lagrange parameter to weight constraints (no edges within set)
versus objective (largest set possible).
sampler_args
Additional keyword parameters are passed to the sampler.
Returns
-------
clique_nodes : list
List of nodes that form a maximum clique, as
determined by the given sampler.
Notes
-----
Samplers by their nature may not return the optimal solution. This
function does not attempt to confirm the quality of the returned
sample.
References
----------
`Maximum Clique on Wikipedia <https://en.wikipedia.org/wiki/Maximum_clique(graph_theory)>`_ | 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 of nodes that form a clique, as
determined by the given sampler.
Returns
-------
is_clique : bool
True if clique_nodes forms a clique.
Example
-------
This example checks two sets of nodes, both derived from a
single Chimera unit cell, for an independent set. The first set is
the horizontal tile's nodes; the second has nodes from the horizontal and
verical tiles.
>>> import dwave_networkx as dnx
>>> G = dnx.chimera_graph(1, 1, 4)
>>> dnx.is_clique(G, [0, 1, 2, 3])
False
>>> dnx.is_clique(G, [0, 4])
True | 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
--------
This example checks whether node 0 is simplicial for two graphs: G, a
single Chimera unit cell, which is bipartite, and K_5, the :math:`K_5`
complete graph.
>>> import dwave_networkx as dnx
>>> import networkx as nx
>>> G = dnx.chimera_graph(1, 1, 4)
>>> K_5 = nx.complete_graph(5)
>>> dnx.is_simplicial(G, 0)
False
>>> dnx.is_simplicial(K_5, 0)
True | 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 neighbors induce a clique
Examples
--------
This example checks whether node 0 is simplicial or almost simplicial for
a :math:`K_5` complete graph with one edge removed.
>>> import dwave_networkx as dnx
>>> import networkx as nx
>>> K_5 = nx.complete_graph(5)
>>> K_5.remove_edge(1,3)
>>> dnx.is_simplicial(K_5, 0)
False
>>> dnx.is_almost_simplicial(K_5, 0)
True | 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 in neighbors)<EOL><DEDENT>u = min(neighbors, key=neighborhood_degree)<EOL>new_lb = len(adj[v])<EOL>if new_lb > lb:<EOL><INDENT>lb = new_lb<EOL><DEDENT>adj[v] = adj[v].union(n for n in adj[u] if n != v)<EOL>for n in adj[v]:<EOL><INDENT>adj[n].add(v)<EOL><DEDENT>for n in adj[u]:<EOL><INDENT>adj[n].discard(u)<EOL><DEDENT>del adj[u]<EOL><DEDENT>return lb<EOL> | Computes a lower bound for the treewidth of graph G.
Parameters
----------
G : NetworkX graph
The graph on which to compute a lower bound on the treewidth.
Returns
-------
lb : int
A lower bound on the treewidth.
Examples
--------
This example computes a lower bound for the treewidth of the :math:`K_7`
complete graph.
>>> import dwave_networkx as dnx
>>> import networkx as nx
>>> K_7 = nx.complete_graph(7)
>>> dnx.minor_min_width(K_7)
6
References
----------
Based on the algorithm presented in [GD]_ | 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>_elim_adj(adj, v)<EOL>order[i] = v<EOL><DEDENT>return upper_bound, order<EOL> | Computes an upper bound on the treewidth of graph G based on
the min-fill heuristic for the elimination ordering.
Parameters
----------
G : NetworkX graph
The graph on which to compute an upper bound for the treewidth.
Returns
-------
treewidth_upper_bound : int
An upper bound on the treewidth of the graph G.
order : list
An elimination order that induces the treewidth.
Examples
--------
This example computes an upper bound for the treewidth of the :math:`K_4`
complete graph.
>>> import dwave_networkx as dnx
>>> import networkx as nx
>>> K_4 = nx.complete_graph(4)
>>> tw, order = dnx.min_fill_heuristic(K_4)
References
----------
Based on the algorithm presented in [GD]_ | 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(adj, v)<EOL>order[i] = v<EOL><DEDENT>return upper_bound, order<EOL> | Computes an upper bound on the treewidth of graph G based on
the min-width heuristic for the elimination ordering.
Parameters
----------
G : NetworkX graph
The graph on which to compute an upper bound for the treewidth.
Returns
-------
treewidth_upper_bound : int
An upper bound on the treewidth of the graph G.
order : list
An elimination order that induces the treewidth.
Examples
--------
This example computes an upper bound for the treewidth of the :math:`K_4`
complete graph.
>>> import dwave_networkx as dnx
>>> import networkx as nx
>>> K_4 = nx.complete_graph(4)
>>> tw, order = dnx.min_width_heuristic(K_4)
References
----------
Based on the algorithm presented in [GD]_ | 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_neighbors[v]<EOL>for u in adj[v]:<EOL><INDENT>if u in labelled_neighbors:<EOL><INDENT>labelled_neighbors[u] += <NUM_LIT:1><EOL><DEDENT><DEDENT>order[-(i + <NUM_LIT:1>)] = v<EOL><DEDENT>for v in order:<EOL><INDENT>dv = len(adj[v])<EOL>if dv > upper_bound:<EOL><INDENT>upper_bound = dv<EOL><DEDENT>_elim_adj(adj, v)<EOL><DEDENT>return upper_bound, order<EOL> | Computes an upper bound on the treewidth of graph G based on
the max-cardinality heuristic for the elimination ordering.
Parameters
----------
G : NetworkX graph
The graph on which to compute an upper bound for the treewidth.
inplace : bool
If True, G will be made an empty graph in the process of
running the function, otherwise the function uses a copy
of G.
Returns
-------
treewidth_upper_bound : int
An upper bound on the treewidth of the graph G.
order : list
An elimination order that induces the treewidth.
Examples
--------
This example computes an upper bound for the treewidth of the :math:`K_4`
complete graph.
>>> import dwave_networkx as dnx
>>> import networkx as nx
>>> K_4 = nx.complete_graph(4)
>>> dnx.max_cardinality_heuristic(K_4)
(3, [3, 1, 0, 2])
References
----------
Based on the algorithm presented in [GD]_ | 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 adj[n]<EOL>return new_edges<EOL> | 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 added by eliminating v. | 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:<EOL><INDENT>raise ValueError('<STR_LIT>')<EOL><DEDENT>return treewidth<EOL> | Calculates the width of the tree decomposition induced by a
variable elimination order.
Parameters
----------
G : NetworkX graph
The graph on which to compute the width of the tree decomposition.
order : list
The elimination order. Must be a list of all of the variables
in G.
Returns
-------
treewidth : int
The width of the tree decomposition induced by order.
Examples
--------
This example computes the width of the tree decomposition for the :math:`K_4`
complete graph induced by an elimination order found through the min-width
heuristic.
>>> import dwave_networkx as dnx
>>> import networkx as nx
>>> K_4 = nx.complete_graph(4)
>>> dnx.min_width_heuristic(K_4)
(3, [1, 2, 0, 3])
>>> dnx.elimination_order_width(K_4, [1, 2, 0, 3])
3 | 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:<EOL><INDENT>ub, order = upperbound, elimination_order<EOL><DEDENT><DEDENT>if treewidth_upperbound is not None and treewidth_upperbound < ub:<EOL><INDENT>ub, order = treewidth_upperbound, []<EOL><DEDENT>best_found = ub, order<EOL>assert f <= ub, "<STR_LIT>"<EOL>if f < ub:<EOL><INDENT>adj = {v: set(G[v]) for v in G}<EOL>best_found = _branch_and_bound(adj, x, g, f, best_found)<EOL><DEDENT>return best_found<EOL> | Computes the treewidth of graph G and a corresponding perfect elimination ordering.
Parameters
----------
G : NetworkX graph
The graph on which to compute the treewidth and perfect elimination ordering.
elimination_order: list (optional, Default None)
An elimination order used as an initial best-known order. If a good
order is provided, it may speed up computation. If not provided, the
initial order is generated using the min-fill heuristic.
treewidth_upperbound : int (optional, Default None)
An upper bound on the treewidth. Note that using
this parameter can result in no returned order.
Returns
-------
treewidth : int
The treewidth of graph G.
order : list
An elimination order that induces the treewidth.
Examples
--------
This example computes the treewidth for the :math:`K_7`
complete graph using an optionally provided elimination order (a sequential
ordering of the nodes, arbitrally chosen).
>>> import dwave_networkx as dnx
>>> import networkx as nx
>>> K_7 = nx.complete_graph(7)
>>> dnx.treewidth_branch_and_bound(K_7, [0, 1, 2, 3, 4, 5, 6])
(6, [0, 1, 2, 3, 4, 5, 6])
References
----------
.. [GD] Gogate & Dechter, "A Complete Anytime Algorithm for Treewidth",
https://arxiv.org/abs/1207.4109 | 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><DEDENT>elif f == ub and not order:<EOL><INDENT>return (f, x + list(adj))<EOL><DEDENT>else:<EOL><INDENT>return best_found<EOL><DEDENT><DEDENT>sorted_adj = sorted((n for n in adj if n not in skipable), key=lambda x: _min_fill_needed_edges(adj, x))<EOL>for n in sorted_adj:<EOL><INDENT>g_s = max(g, len(adj[n]))<EOL>next_skipable = adj[n]<EOL>if prune6p2(x, n, next_skipable):<EOL><INDENT>continue<EOL><DEDENT>adj_s = {v: adj[v].copy() for v in adj} <EOL>edges_n = _elim_adj(adj_s, n)<EOL>x_s = x + [n] <EOL>if prune6p4(edges_n):<EOL><INDENT>continue<EOL><DEDENT>_theorem5p4(adj_s, ub)<EOL>f_s = max(g_s, minor_min_width(adj_s))<EOL>g_s, f_s, as_list = _graph_reduction(adj_s, x_s, g_s, f_s)<EOL>if f_s < ub:<EOL><INDENT>best_found = _branch_and_bound(adj_s, x_s, g_s, f_s, best_found,<EOL>next_skipable, theorem6p2=theorem6p2)<EOL>ub, __ = best_found<EOL><DEDENT>prunable = explored6p2(x, n, next_skipable)<EOL>current6p2.append(prunable)<EOL>explored6p4(edges_n)<EOL><DEDENT>for prunable in current6p2:<EOL><INDENT>finished6p2(prunable)<EOL><DEDENT>return best_found<EOL> | 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
skipable: vertices that can be skipped according to Lemma 5.3
theorem6p2: terms that have been explored/can be pruned according to Theorem 6.2 | 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(adj, n)<EOL><DEDENT>as_nodes = {v for v in adj if len(adj[v]) <= f and is_almost_simplicial(adj, v)}<EOL><DEDENT>return g, f, as_list<EOL> | 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].add(u)<EOL><DEDENT>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><DEDENT> | 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:2>]), x[-<NUM_LIT:1>], x[-<NUM_LIT:2>])<EOL>pruning_set.add(prunable)<EOL><DEDENT><DEDENT>return _prune, _explored<EOL> | 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><INDENT>prunable = (tuple(x), a, frozenset(nbrs_a)) <EOL>pruning_set2.add(prunable)<EOL>return prunable<EOL><DEDENT>def _finished2(prunable):<EOL><INDENT>pruning_set2.remove(prunable)<EOL><DEDENT>return _prune2, _explored2, _finished2<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) <EOL>pruning_set3.add(prunable)<EOL><DEDENT><DEDENT>return _prune3, _explored3<EOL> | 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 level of recursion). | 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[v]))<EOL>horiz, verti = rooted_tile(adj, root, t)<EOL>while len(chimera_indices) < len(adj):<EOL><INDENT>new_indices = {}<EOL>if row == <NUM_LIT:0>:<EOL><INDENT>for si, v in enumerate(horiz):<EOL><INDENT>new_indices[v] = (row, col, <NUM_LIT:0>, si)<EOL><DEDENT><DEDENT>else:<EOL><INDENT>for v in horiz:<EOL><INDENT>north = [u for u in adj[v] if u in chimera_indices]<EOL>assert len(north) == <NUM_LIT:1><EOL>i, j, u, si = chimera_indices[north[<NUM_LIT:0>]]<EOL>assert i == row - <NUM_LIT:1> and j == col and u == <NUM_LIT:0><EOL>new_indices[v] = (row, col, <NUM_LIT:0>, si)<EOL><DEDENT><DEDENT>if col == <NUM_LIT:0>:<EOL><INDENT>for si, v in enumerate(verti):<EOL><INDENT>new_indices[v] = (row, col, <NUM_LIT:1>, si)<EOL><DEDENT><DEDENT>else:<EOL><INDENT>for v in verti:<EOL><INDENT>east = [u for u in adj[v] if u in chimera_indices]<EOL>assert len(east) == <NUM_LIT:1><EOL>i, j, u, si = chimera_indices[east[<NUM_LIT:0>]]<EOL>assert i == row and j == col - <NUM_LIT:1> and u == <NUM_LIT:1><EOL>new_indices[v] = (row, col, <NUM_LIT:1>, si)<EOL><DEDENT><DEDENT>chimera_indices.update(new_indices)<EOL>root_neighbours = [v for v in adj[root] if v not in chimera_indices]<EOL>if len(root_neighbours) == <NUM_LIT:1>:<EOL><INDENT>root = root_neighbours[<NUM_LIT:0>]<EOL>horiz, verti = rooted_tile(adj, root, t)<EOL>row += <NUM_LIT:1><EOL><DEDENT>else:<EOL><INDENT>assert not root_neighbours <EOL>vert_root = [v for v in chimera_indices if chimera_indices[v] == (<NUM_LIT:0>, col, <NUM_LIT:1>, <NUM_LIT:0>)][<NUM_LIT:0>]<EOL>vert_root_neighbours = [v for v in adj[vert_root] if v not in chimera_indices]<EOL>if vert_root_neighbours:<EOL><INDENT>verti, horiz = rooted_tile(adj, vert_root_neighbours[<NUM_LIT:0>], t)<EOL>root = next(iter(horiz))<EOL>row = <NUM_LIT:0><EOL>col += <NUM_LIT:1><EOL><DEDENT><DEDENT><DEDENT>return chimera_indices<EOL> | Returns a mapping from the labels of G to chimera-indexed labeling.
Parameters
----------
G : NetworkX graph
A Chimera-structured graph.
t : int (optional, default 4)
Size of the shore within each Chimera tile.
Returns
-------
chimera_indices: dict
A mapping from the current labels to a 4-tuple of Chimera indices. | 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 an Ising
equation or a Quadratic Unconstrained Binary Optimization
Problem (QUBO). A sampler is expected to have a 'sample_qubo'
and 'sample_ising' method. A sampler is expected to return an
iterable of samples, in order of increasing energy. If no
sampler is provided, one must be provided using the
`set_default_sampler` function.
fixed_variables : dict
A dictionary of variable assignments to be fixed in the markov network.
return_sampleset : bool (optional, default=False)
If True, returns a :obj:`dimod.SampleSet` rather than a list of samples.
**sampler_args
Additional keyword parameters are passed to the sampler.
Returns
-------
samples : list[dict]/:obj:`dimod.SampleSet`
A list of samples ordered from low-to-high energy or a sample set.
Examples
--------
>>> import dimod
...
>>> potentials = {('a', 'b'): {(0, 0): -1,
... (0, 1): .5,
... (1, 0): .5,
... (1, 1): 2}}
>>> MN = dnx.markov_network(potentials)
>>> sampler = dimod.ExactSolver()
>>> samples = dnx.sample_markov_network(MN, sampler)
>>> samples[0]
{'a': 0, 'b': 0}
>>> import dimod
...
>>> potentials = {('a', 'b'): {(0, 0): -1,
... (0, 1): .5,
... (1, 0): .5,
... (1, 1): 2}}
>>> MN = dnx.markov_network(potentials)
>>> sampler = dimod.ExactSolver()
>>> samples = dnx.sample_markov_network(MN, sampler, return_sampleset=True)
>>> samples.first
Sample(sample={'a': 0, 'b': 0}, energy=-1.0, num_occurrences=1)
>>> import dimod
...
>>> potentials = {('a', 'b'): {(0, 0): -1,
... (0, 1): .5,
... (1, 0): .5,
... (1, 1): 2},
... ('b', 'c'): {(0, 0): -9,
... (0, 1): 1.2,
... (1, 0): 7.2,
... (1, 1): 5}}
>>> MN = dnx.markov_network(potentials)
>>> sampler = dimod.ExactSolver()
>>> samples = dnx.sample_markov_network(MN, sampler, fixed_variables={'b': 0})
>>> samples[0]
{'a': 0, 'c': 0, 'b': 0}
Notes
-----
Samplers by their nature may not return the optimal solution. This
function does not attempt to confirm the quality of the returned
sample. | 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 - phi0)<EOL>bqm.add_offset(phi0)<EOL><DEDENT>for u, v, ddict in MN.edges(data=True, default=None):<EOL><INDENT>potential = ddict.get('<STR_LIT>', None)<EOL>if potential is None:<EOL><INDENT>continue<EOL><DEDENT>order = ddict['<STR_LIT>']<EOL>u, v = order<EOL>phi00 = potential[(<NUM_LIT:0>, <NUM_LIT:0>)]<EOL>phi01 = potential[(<NUM_LIT:0>, <NUM_LIT:1>)]<EOL>phi10 = potential[(<NUM_LIT:1>, <NUM_LIT:0>)]<EOL>phi11 = potential[(<NUM_LIT:1>, <NUM_LIT:1>)]<EOL>bqm.add_variable(u, phi10 - phi00)<EOL>bqm.add_variable(v, phi01 - phi00)<EOL>bqm.add_interaction(u, v, phi11 - phi10 - phi01 + phi00)<EOL>bqm.add_offset(phi00)<EOL><DEDENT>return bqm<EOL> | 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>']<EOL>if sign > <NUM_LIT:0> and colors[u] != colors[v]:<EOL><INDENT>frustrated_edges[(u, v)] = data<EOL><DEDENT>elif sign < <NUM_LIT:0> and colors[u] == colors[v]:<EOL><INDENT>frustrated_edges[(u, v)] = data<EOL><DEDENT><DEDENT>return frustrated_edges, colors<EOL> | Returns an approximate set of frustrated edges and a bicoloring.
A signed social network graph is a graph whose signed edges
represent friendly/hostile interactions between nodes. A
signed social network is considered balanced if it can be cleanly
divided into two factions, where all relations within a faction are
friendly, and all relations between factions are hostile. The measure
of imbalance or frustration is the minimum number of edges that
violate this rule.
Parameters
----------
S : NetworkX graph
A social graph on which each edge has a 'sign'
attribute with a numeric value.
sampler
A binary quadratic model sampler. A sampler is a process that
samples from low energy states in models defined by an Ising
equation or a Quadratic Unconstrainted Binary Optimization
Problem (QUBO). A sampler is expected to have a 'sample_qubo'
and 'sample_ising' method. A sampler is expected to return an
iterable of samples, in order of increasing energy. If no
sampler is provided, one must be provided using the
`set_default_sampler` function.
sampler_args
Additional keyword parameters are passed to the sampler.
Returns
-------
frustrated_edges : dict
A dictionary of the edges that violate the edge sign. The imbalance
of the network is the length of frustrated_edges.
colors: dict
A bicoloring of the nodes into two factions.
Raises
------
ValueError
If any edge does not have a 'sign' attribute.
Examples
--------
>>> import dimod
>>> sampler = dimod.ExactSolver()
>>> S = nx.Graph()
>>> S.add_edge('Alice', 'Bob', sign=1) # Alice and Bob are friendly
>>> S.add_edge('Alice', 'Eve', sign=-1) # Alice and Eve are hostile
>>> S.add_edge('Bob', 'Eve', sign=-1) # Bob and Eve are hostile
>>> frustrated_edges, colors = dnx.structural_imbalance(S, sampler)
>>> print(frustrated_edges)
{}
>>> print(colors) # doctest: +SKIP
{'Alice': 0, 'Bob': 0, 'Eve': 1}
>>> S.add_edge('Ted', 'Bob', sign=1) # Ted is friendly with all
>>> S.add_edge('Ted', 'Alice', sign=1)
>>> S.add_edge('Ted', 'Eve', sign=1)
>>> frustrated_edges, colors = dnx.structural_imbalance(S, sampler)
>>> print(frustrated_edges)
{('Ted', 'Eve'): {'sign': 1}}
>>> print(colors) # doctest: +SKIP
{'Bob': 1, 'Ted': 1, 'Alice': 1, 'Eve': 0}
Notes
-----
Samplers by their nature may not return the optimal solution. This
function does not attempt to confirm the quality of the returned
sample.
References
----------
`Ising model on Wikipedia <https://en.wikipedia.org/wiki/Ising_model>`_
.. [FIA] Facchetti, G., Iacono G., and Altafini C. (2011). Computing
global structural balance in large-scale signed social networks.
PNAS, 108, no. 52, 20953-20958 | 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, where all relations within a faction are
friendly, and all relations between factions are hostile. The measure
of imbalance or frustration is the minimum number of edges that
violate this rule.
Parameters
----------
S : NetworkX graph
A social graph on which each edge has a 'sign' attribute with a numeric value.
Returns
-------
h : dict
The linear biases of the Ising problem. Each variable in the Ising problem represent
a node in the signed social network. The solution that minimized the Ising problem
will assign each variable a value, either -1 or 1. This bi-coloring defines the factions.
J : dict
The quadratic biases of the Ising problem.
Raises
------
ValueError
If any edge does not have a 'sign' attribute.
Examples
--------
>>> import dimod
>>> from dwave_networkx.algorithms.social import structural_imbalance_ising
...
>>> S = nx.Graph()
>>> S.add_edge('Alice', 'Bob', sign=1) # Alice and Bob are friendly
>>> S.add_edge('Alice', 'Eve', sign=-1) # Alice and Eve are hostile
>>> S.add_edge('Bob', 'Eve', sign=-1) # Bob and Eve are hostile
...
>>> h, J = structural_imbalance_ising(S)
>>> h # doctest: +SKIP
{'Alice': 0.0, 'Bob': 0.0, 'Eve': 0.0}
>>> J # doctest: +SKIP
{('Alice', 'Bob'): -1.0, ('Alice', 'Eve'): 1.0, ('Bob', 'Eve'): 1.0} | 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 minimum weighted
vertex cover is the vertex cover of minimum total node weight.
Parameters
----------
G : NetworkX graph
weight : string, optional (default None)
If None, every node has equal weight. If a string, use this node
attribute as the node weight. A node without this attribute is
assumed to have max weight.
sampler
A binary quadratic model sampler. A sampler is a process that
samples from low energy states in models defined by an Ising
equation or a Quadratic Unconstrained Binary Optimization
Problem (QUBO). A sampler is expected to have a 'sample_qubo'
and 'sample_ising' method. A sampler is expected to return an
iterable of samples, in order of increasing energy. If no
sampler is provided, one must be provided using the
`set_default_sampler` function.
sampler_args
Additional keyword parameters are passed to the sampler.
Returns
-------
vertex_cover : list
List of nodes that the form a the minimum weighted vertex cover, as
determined by the given sampler.
Notes
-----
Samplers by their nature may not return the optimal solution. This
function does not attempt to confirm the quality of the returned
sample.
https://en.wikipedia.org/wiki/Vertex_cover
https://en.wikipedia.org/wiki/Quadratic_unconstrained_binary_optimization
References
----------
Based on the formulation presented in [AL]_ | 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
is the vertex cover of smallest size.
Parameters
----------
G : NetworkX graph
The graph on which to find a minimum vertex cover.
sampler
A binary quadratic model sampler. A sampler is a process that
samples from low energy states in models defined by an Ising
equation or a Quadratic Unconstrained Binary Optimization
Problem (QUBO). A sampler is expected to have a 'sample_qubo'
and 'sample_ising' method. A sampler is expected to return an
iterable of samples, in order of increasing energy. If no
sampler is provided, one must be provided using the
`set_default_sampler` function.
sampler_args
Additional keyword parameters are passed to the sampler.
Returns
-------
vertex_cover : list
List of nodes that form a minimum vertex cover, as
determined by the given sampler.
Examples
--------
This example uses a sampler from
`dimod <https://github.com/dwavesystems/dimod>`_ to find a minimum vertex
cover for a Chimera unit cell. Both the horizontal (vertices 0,1,2,3) and
vertical (vertices 4,5,6,7) tiles connect to all 16 edges, so repeated
executions can return either set.
>>> import dwave_networkx as dnx
>>> import dimod
>>> sampler = dimod.ExactSolver() # small testing sampler
>>> G = dnx.chimera_graph(1, 1, 4)
>>> G.remove_node(7) # to give a unique solution
>>> dnx.min_vertex_cover(G, sampler)
[4, 5, 6]
Notes
-----
Samplers by their nature may not return the optimal solution. This
function does not attempt to confirm the quality of the returned
sample.
References
----------
https://en.wikipedia.org/wiki/Vertex_cover
https://en.wikipedia.org/wiki/Quadratic_unconstrained_binary_optimization
.. [AL] Lucas, A. (2014). Ising formulations of many NP problems.
Frontiers in Physics, Volume 2, Article 5. | 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_cover :
Iterable of nodes.
Returns
-------
is_cover : bool
True if the given iterable forms a vertex cover.
Examples
--------
This example checks two covers for a graph, G, of a single Chimera
unit cell. The first uses the set of the four horizontal qubits, which
do constitute a cover; the second set removes one node.
>>> import dwave_networkx as dnx
>>> G = dnx.chimera_graph(1, 1, 4)
>>> cover = [0, 1, 2, 3]
>>> dnx.is_vertex_cover(G,cover)
True
>>> cover = [0, 1, 2]
>>> dnx.is_vertex_cover(G,cover)
False | 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.
Parameters
----------
G : NetworkX graph
The graph on which to find a maximum cut.
sampler
A binary quadratic model sampler. A sampler is a process that
samples from low energy states in models defined by an Ising
equation or a Quadratic Unconstrained Binary Optimization
Problem (QUBO). A sampler is expected to have a 'sample_qubo'
and 'sample_ising' method. A sampler is expected to return an
iterable of samples, in order of increasing energy. If no
sampler is provided, one must be provided using the
`set_default_sampler` function.
sampler_args
Additional keyword parameters are passed to the sampler.
Returns
-------
S : set
A maximum cut of G.
Example
-------
This example uses a sampler from
`dimod <https://github.com/dwavesystems/dimod>`_ to find a maximum cut
for a graph of a Chimera unit cell created using the `chimera_graph()`
function.
>>> import dimod
>>> import dwave_networkx as dnx
>>> samplerSA = dimod.SimulatedAnnealingSampler()
>>> G = dnx.chimera_graph(1, 1, 4)
>>> cut = dnx.maximum_cut(G, samplerSA)
Notes
-----
Samplers by their nature may not return the optimal solution. This
function does not attempt to confirm the quality of the returned
sample. | 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 in G if sample[v] >= <NUM_LIT:0>)<EOL> | Returns an approximate weighted maximum cut.
Defines an Ising problem with ground states corresponding to
a weighted maximum cut and uses the sampler to sample from it.
A weighted maximum cut is a subset S of the vertices of G that
maximizes the sum of the edge weights between S and its
complementary subset.
Parameters
----------
G : NetworkX graph
The graph on which to find a weighted maximum cut. Each edge in G should
have a numeric `weight` attribute.
sampler
A binary quadratic model sampler. A sampler is a process that
samples from low energy states in models defined by an Ising
equation or a Quadratic Unconstrained Binary Optimization
Problem (QUBO). A sampler is expected to have a 'sample_qubo'
and 'sample_ising' method. A sampler is expected to return an
iterable of samples, in order of increasing energy. If no
sampler is provided, one must be provided using the
`set_default_sampler` function.
sampler_args
Additional keyword parameters are passed to the sampler.
Returns
-------
S : set
A maximum cut of G.
Example
-------
This example uses a sampler from
`dimod <https://github.com/dwavesystems/dimod>`_ to find a weighted maximum
cut for a graph of a Chimera unit cell. The graph is created using the
`chimera_graph()` function with weights added to all its edges such that
those incident to nodes {6, 7} have weight -1 while the others are +1. A
weighted maximum cut should cut as many of the latter and few of the former
as possible.
>>> import dimod
>>> import dwave_networkx as dnx
>>> samplerSA = dimod.SimulatedAnnealingSampler()
>>> G = dnx.chimera_graph(1, 1, 4)
>>> for u, v in G.edges:
....: if (u >= 6) | (v >=6):
....: G[u][v]['weight']=-1
....: else: G[u][v]['weight']=1
....:
>>> dnx.weighted_maximum_cut(G, samplerSA)
{4, 5}
Notes
-----
Samplers by their nature may not return the optimal solution. This
function does not attempt to confirm the quality of the returned
sample. | 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 maximum
independent set is an independent set of maximum total node weight.
Parameters
----------
G : NetworkX graph
The graph on which to find a maximum cut weighted independent set.
weight : string, optional (default None)
If None, every node has equal weight. If a string, use this node
attribute as the node weight. A node without this attribute is
assumed to have max weight.
sampler
A binary quadratic model sampler. A sampler is a process that
samples from low energy states in models defined by an Ising
equation or a Quadratic Unconstrained Binary Optimization
Problem (QUBO). A sampler is expected to have a 'sample_qubo'
and 'sample_ising' method. A sampler is expected to return an
iterable of samples, in order of increasing energy. If no
sampler is provided, one must be provided using the
`set_default_sampler` function.
lagrange : optional (default 2)
Lagrange parameter to weight constraints (no edges within set)
versus objective (largest set possible).
sampler_args
Additional keyword parameters are passed to the sampler.
Returns
-------
indep_nodes : list
List of nodes that form a maximum weighted independent set, as
determined by the given sampler.
Notes
-----
Samplers by their nature may not return the optimal solution. This
function does not attempt to confirm the quality of the returned
sample.
References
----------
`Independent Set on Wikipedia <https://en.wikipedia.org/wiki/Independent_set_(graph_theory)>`_
`QUBO on Wikipedia <https://en.wikipedia.org/wiki/Quadratic_unconstrained_binary_optimization>`_
.. [AL] Lucas, A. (2014). Ising formulations of many NP problems.
Frontiers in Physics, Volume 2, Article 5. | 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 set is an independent set of largest possible size.
Parameters
----------
G : NetworkX graph
The graph on which to find a maximum cut independent set.
sampler
A binary quadratic model sampler. A sampler is a process that
samples from low energy states in models defined by an Ising
equation or a Quadratic Unconstrained Binary Optimization
Problem (QUBO). A sampler is expected to have a 'sample_qubo'
and 'sample_ising' method. A sampler is expected to return an
iterable of samples, in order of increasing energy. If no
sampler is provided, one must be provided using the
`set_default_sampler` function.
lagrange : optional (default 2)
Lagrange parameter to weight constraints (no edges within set)
versus objective (largest set possible).
sampler_args
Additional keyword parameters are passed to the sampler.
Returns
-------
indep_nodes : list
List of nodes that form a maximum independent set, as
determined by the given sampler.
Example
-------
This example uses a sampler from
`dimod <https://github.com/dwavesystems/dimod>`_ to find a maximum
independent set for a graph of a Chimera unit cell created using the
`chimera_graph()` function.
>>> import dimod
>>> sampler = dimod.SimulatedAnnealingSampler()
>>> G = dnx.chimera_graph(1, 1, 4)
>>> indep_nodes = dnx.maximum_independent_set(G, sampler)
Notes
-----
Samplers by their nature may not return the optimal solution. This
function does not attempt to confirm the quality of the returned
sample.
References
----------
`Independent Set on Wikipedia <https://en.wikipedia.org/wiki/Independent_set_(graph_theory)>`_
`QUBO on Wikipedia <https://en.wikipedia.org/wiki/Quadratic_unconstrained_binary_optimization>`_
.. [AL] Lucas, A. (2014). Ising formulations of many NP problems.
Frontiers in Physics, Volume 2, Article 5. | 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
List of nodes that form a maximum independent set, as
determined by the given sampler.
Returns
-------
is_independent : bool
True if indep_nodes form an independent set.
Example
-------
This example checks two sets of nodes, both derived from a
single Chimera unit cell, for an independent set. The first set is
the horizontal tile's nodes; the second has nodes from the horizontal and
verical tiles.
>>> import dwave_networkx as dnx
>>> G = dnx.chimera_graph(1, 1, 4)
>>> dnx.is_independent_set(G, [0, 1, 2, 3])
True
>>> dnx.is_independent_set(G, [0, 4])
False | 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 attribute is
assumed to have max weight.
lagrange : optional (default 2)
Lagrange parameter to weight constraints (no edges within set)
versus objective (largest set possible).
Returns
-------
QUBO : dict
The QUBO with ground states corresponding to a maximum weighted independent set.
Examples
--------
>>> from dwave_networkx.algorithms.independent_set import maximum_weighted_independent_set_qubo
...
>>> G = nx.path_graph(3)
>>> Q = maximum_weighted_independent_set_qubo(G, weight='weight', lagrange=2.0)
>>> Q[(0, 0)]
-1.0
>>> Q[(1, 1)]
-1.0
>>> Q[(0, 1)]
2.0 | 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>])<EOL>return list((x[<NUM_LIT:0>] for x in route))<EOL> | Returns an approximate minimum traveling salesperson route.
Defines a QUBO with ground states corresponding to the
minimum routes and uses the sampler to sample
from it.
A route is a cycle in the graph that reaches each node exactly once.
A minimum route is a route with the smallest total edge weight.
Parameters
----------
G : NetworkX graph
The graph on which to find a minimum traveling salesperson route.
This should be a complete graph with non-zero weights on every edge.
sampler :
A binary quadratic model sampler. A sampler is a process that
samples from low energy states in models defined by an Ising
equation or a Quadratic Unconstrained Binary Optimization
Problem (QUBO). A sampler is expected to have a 'sample_qubo'
and 'sample_ising' method. A sampler is expected to return an
iterable of samples, in order of increasing energy. If no
sampler is provided, one must be provided using the
`set_default_sampler` function.
lagrange : optional (default 2)
Lagrange parameter to weight constraints (visit every city once)
versus objective (shortest distance route).
weight : optional (default 'weight')
The name of the edge attribute containing the weight.
sampler_args :
Additional keyword parameters are passed to the sampler.
Returns
-------
route : list
List of nodes in order to be visited on a route
Examples
--------
This example uses a `dimod <https://github.com/dwavesystems/dimod>`_ sampler
to find a minimum route in a five-cities problem.
>>> import dwave_networkx as dnx
>>> import networkx as nx
>>> import dimod
...
>>> G = nx.complete_graph(4)
>>> G.add_weighted_edges_from({(0, 1, 1), (0, 2, 2), (0, 3, 3), (1, 2, 3),
... (1, 3, 4), (2, 3, 5)})
>>> dnx.traveling_salesman(G, dimod.ExactSolver())
[2, 1, 0, 3]
Notes
-----
Samplers by their nature may not return the optimal solution. This
function does not attempt to confirm the quality of the returned
sample. | 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>for pos_2 in range(pos_1+<NUM_LIT:1>, N):<EOL><INDENT>Q[((node, pos_1), (node, pos_2))] += <NUM_LIT>*lagrange<EOL><DEDENT><DEDENT><DEDENT>for pos in range(N):<EOL><INDENT>for node_1 in G:<EOL><INDENT>Q[((node_1, pos), (node_1, pos))] -= lagrange<EOL>for node_2 in set(G)-{node_1}:<EOL><INDENT>Q[((node_1, pos), (node_2, pos))] += <NUM_LIT>*lagrange<EOL><DEDENT><DEDENT><DEDENT>for u, v in itertools.combinations(G.nodes, <NUM_LIT:2>):<EOL><INDENT>for pos in range(N):<EOL><INDENT>nextpos = (pos + <NUM_LIT:1>) % N<EOL>Q[((u, pos), (v, nextpos))] += G[u][v][weight]<EOL>Q[((v, pos), (u, nextpos))] += G[u][v][weight]<EOL><DEDENT><DEDENT>return Q<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 graph in which each edge has a attribute giving its weight.
lagrange : number, optional (default 2)
Lagrange parameter to weight constraints (no edges within set)
versus objective (largest set possible).
weight : optional (default 'weight')
The name of the edge attribute containing the weight.
Returns
-------
QUBO : dict
The QUBO with ground states corresponding to a minimum travelling
salesperson route. | 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.
Returns
-------
is_valid : bool
True if route forms a valid travelling salesperson route. | 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 = len(G.edges) <EOL>if not n_edges:<EOL><INDENT>return {node: <NUM_LIT:0> for node in G}<EOL><DEDENT>if n_edges == n_nodes * (n_nodes - <NUM_LIT:1>) // <NUM_LIT:2>:<EOL><INDENT>return {node: color for color, node in enumerate(G)}<EOL><DEDENT>chi_ub = _chromatic_number_upper_bound(G, n_nodes, n_edges)<EOL>partial_coloring, possible_colors, chi_lb = _partial_precolor(G, chi_ub)<EOL>counter = itertools.count()<EOL>x_vars = {v: {c: next(counter) for c in possible_colors[v]} for v in possible_colors}<EOL>Q_neighbor = _vertex_different_colors_qubo(G, x_vars)<EOL>Q_vertex = _vertex_one_color_qubo(x_vars)<EOL>Q_min_color = _minimum_coloring_qubo(x_vars, chi_lb, chi_ub, magnitude=<NUM_LIT>)<EOL>Q = Q_neighbor<EOL>for (u, v), bias in iteritems(Q_vertex):<EOL><INDENT>if (u, v) in Q:<EOL><INDENT>Q[(u, v)] += bias<EOL><DEDENT>elif (v, u) in Q:<EOL><INDENT>Q[(v, u)] += bias<EOL><DEDENT>else:<EOL><INDENT>Q[(u, v)] = bias<EOL><DEDENT><DEDENT>for (v, v), bias in iteritems(Q_min_color):<EOL><INDENT>if (v, v) in Q:<EOL><INDENT>Q[(v, v)] += bias<EOL><DEDENT>else:<EOL><INDENT>Q[(v, v)] = bias<EOL><DEDENT><DEDENT>response = sampler.sample_qubo(Q, **sampler_args)<EOL>sample = next(iter(response))<EOL>for v in x_vars:<EOL><INDENT>for c in x_vars[v]:<EOL><INDENT>if sample[x_vars[v][c]]:<EOL><INDENT>partial_coloring[v] = c<EOL><DEDENT><DEDENT><DEDENT>return partial_coloring<EOL> | Returns an approximate minimum vertex coloring.
Vertex coloring is the problem of assigning a color to the
vertices of a graph in a way that no adjacent vertices have the
same color. A minimum vertex coloring is the problem of solving
the vertex coloring problem using the smallest number of colors.
Since neighboring vertices must satisfy a constraint of having
different colors, the problem can be posed as a binary constraint
satisfaction problem.
Defines a QUBO with ground states corresponding to minimum
vertex colorings and uses the sampler to sample from it.
Parameters
----------
G : NetworkX graph
The graph on which to find a minimum vertex coloring.
sampler
A binary quadratic model sampler. A sampler is a process that
samples from low energy states in models defined by an Ising
equation or a Quadratic Unconstrained Binary Optimization
Problem (QUBO). A sampler is expected to have a 'sample_qubo'
and 'sample_ising' method. A sampler is expected to return an
iterable of samples, in order of increasing energy. If no
sampler is provided, one must be provided using the
`set_default_sampler` function.
sampler_args
Additional keyword parameters are passed to the sampler.
Returns
-------
coloring : dict
A coloring for each vertex in G such that no adjacent nodes
share the same color. A dict of the form {node: color, ...}
Example
-------
This example colors a single Chimera unit cell. It colors the four
horizontal qubits one color (0) and the four vertical qubits another (1).
>>> # Set up a sampler; this example uses a sampler from dimod https://github.com/dwavesystems/dimod
>>> import dimod
>>> import dwave_networkx as dnx
>>> samplerSA = dimod.SimulatedAnnealingSampler()
>>> # Create a graph and color it
>>> G = dnx.chimera_graph(1, 1, 4)
>>> colors = dnx.min_vertex_coloring(G, sampler=samplerSA)
>>> colors
{0: 0, 1: 0, 2: 0, 3: 0, 4: 1, 5: 1, 6: 1, 7: 1}
References
----------
.. [DWMP] Dahl, E., "Programming the D-Wave: Map Coloring Problem",
https://www.dwavesys.com/sites/default/files/Map%20Coloring%20WP2.pdf
Notes
-----
Samplers by their nature may not return the optimal solution. This
function does not attempt to confirm the quality of the returned
sample. | 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><DEDENT><DEDENT>return Q<EOL> | 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 partial_coloring}<EOL>for v, color in iteritems(partial_coloring):<EOL><INDENT>for u in G[v]:<EOL><INDENT>if u in possible_colors:<EOL><INDENT>possible_colors[u].discard(color)<EOL><DEDENT><DEDENT><DEDENT>return partial_coloring, possible_colors, chi_lb<EOL> | In order to reduce the number of variables in the QUBO, we want to
color as many nodes as possible without affecting the min vertex
coloring. Without loss of generality, we can choose a single maximal
clique and color each node in it uniquely.
Returns
-------
partial_coloring : dict
A dict describing a partial coloring of the nodes of G. Of the form
{node: color, ...}.
possible_colors : dict
A dict giving the possible colors for each node in G not already
colored. Of the form {node: set([color, ...]), ...}.
chi_lb : int
A lower bound on the chromatic number chi.
Notes
-----
partial_coloring.keys() and possible_colors.keys() should be
disjoint. | 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 = leading, node2<EOL><DEDENT>else:<EOL><INDENT>trailing, leading = leading, node1<EOL><DEDENT>n_visited += <NUM_LIT:1><EOL><DEDENT>return n_visited == len(G)<EOL> | Determines whether the given graph is a cycle or circle graph.
A cycle graph or circular graph is a graph that consists of a single cycle.
https://en.wikipedia.org/wiki/Cycle_graph
Parameters
----------
G : NetworkX graph
Returns
-------
is_cycle : bool
True if the graph consists of a single cycle. | 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
-------
is_vertex_coloring : bool
True if the given coloring defines a vertex coloring; that is, no
two adjacent vertices share a color.
Example
-------
This example colors checks two colorings for a graph, G, of a single Chimera
unit cell. The first uses one color (0) for the four horizontal qubits
and another (1) for the four vertical qubits, in which case there are
no adjacencies; the second coloring swaps the color of one node.
>>> G = dnx.chimera_graph(1,1,4)
>>> colors = {0: 0, 1: 0, 2: 0, 3: 0, 4: 1, 5: 1, 6: 1, 7: 1}
>>> dnx.is_vertex_coloring(G, colors)
True
>>> colors[4]=0
>>> dnx.is_vertex_coloring(G, colors)
False | 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_qubo(G, edge_mapping, magnitude=A)<EOL>for edge, bias in Qm.items():<EOL><INDENT>if edge not in Q:<EOL><INDENT>Q[edge] = bias<EOL><DEDENT>else:<EOL><INDENT>Q[edge] += bias<EOL><DEDENT><DEDENT>response = sampler.sample_qubo(Q, **sampler_args)<EOL>sample = next(iter(response))<EOL>return set(edge for edge in G.edges if sample[edge_mapping[edge]] > <NUM_LIT:0>)<EOL> | Finds an approximate maximal matching.
Defines a QUBO with ground states corresponding to a maximal
matching and uses the sampler to sample from it.
A matching is a subset of edges in which no node occurs more than
once. A maximal matching is one in which no edges from G can be
added without violating the matching rule.
Parameters
----------
G : NetworkX graph
The graph on which to find a maximal matching.
sampler
A binary quadratic model sampler. A sampler is a process that
samples from low energy states in models defined by an Ising
equation or a Quadratic Unconstrained Binary Optimization
Problem (QUBO). A sampler is expected to have a 'sample_qubo'
and 'sample_ising' method. A sampler is expected to return an
iterable of samples, in order of increasing energy. If no
sampler is provided, one must be provided using the
`set_default_sampler` function.
sampler_args
Additional keyword parameters are passed to the sampler.
Returns
-------
matching : set
A maximal matching of the graph.
Notes
-----
Samplers by their nature may not return the optimal solution. This
function does not attempt to confirm the quality of the returned
sample.
References
----------
`Matching on Wikipedia <https://en.wikipedia.org/wiki/Matching_(graph_theory)>`_
`QUBO on Wikipedia <https://en.wikipedia.org/wiki/Quadratic_unconstrained_binary_optimization>`_
Based on the formulation presented in [AL]_ | 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=B)<EOL>Qm = _matching_qubo(G, edge_mapping, magnitude=A)<EOL>for edge, bias in Qm.items():<EOL><INDENT>if edge not in Q:<EOL><INDENT>Q[edge] = bias<EOL><DEDENT>else:<EOL><INDENT>Q[edge] += bias<EOL><DEDENT><DEDENT>for v in set(edge_mapping.values()):<EOL><INDENT>if (v, v) not in Q:<EOL><INDENT>Q[(v, v)] = C<EOL><DEDENT>else:<EOL><INDENT>Q[(v, v)] += C<EOL><DEDENT><DEDENT>response = sampler.sample_qubo(Q, **sampler_args)<EOL>sample = next(iter(response))<EOL>return set(edge for edge in G.edges if sample[edge_mapping[edge]] > <NUM_LIT:0>)<EOL> | 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
added without violating the matching rule. A minimum maximal
matching is the smallest maximal matching for G.
Parameters
----------
G : NetworkX graph
The graph on which to find a minimum maximal matching.
sampler
A binary quadratic model sampler. A sampler is a process that
samples from low energy states in models defined by an Ising
equation or a Quadratic Unconstrained Binary Optimization
Problem (QUBO). A sampler is expected to have a 'sample_qubo'
and 'sample_ising' method. A sampler is expected to return an
iterable of samples, in order of increasing energy. If no
sampler is provided, one must be provided using the
`set_default_sampler` function.
sampler_args
Additional keyword parameters are passed to the sampler.
Returns
-------
matching : set
A minimum maximal matching of the graph.
Example
-------
This example uses a sampler from
`dimod <https://github.com/dwavesystems/dimod>`_ to find a minimum maximal
matching for a Chimera unit cell.
>>> import dimod
>>> sampler = dimod.ExactSolver()
>>> G = dnx.chimera_graph(1, 1, 4)
>>> matching = dnx.min_maximal_matching(G, sampler)
Notes
-----
Samplers by their nature may not return the optimal solution. This
function does not attempt to confirm the quality of the returned
sample.
References
----------
`Matching on Wikipedia <https://en.wikipedia.org/wiki/Matching_(graph_theory)>`_
`QUBO on Wikipedia <https://en.wikipedia.org/wiki/Quadratic_unconstrained_binary_optimization>`_
.. [AL] Lucas, A. (2014). Ising formulations of many NP problems.
Frontiers in Physics, Volume 2, Article 5. | f14391:m1 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.