当前位置: 首页>>代码示例>>Python>>正文


Python dimod.Vartype方法代码示例

本文整理汇总了Python中dimod.Vartype方法的典型用法代码示例。如果您正苦于以下问题:Python dimod.Vartype方法的具体用法?Python dimod.Vartype怎么用?Python dimod.Vartype使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在dimod的用法示例。


在下文中一共展示了dimod.Vartype方法的11个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。

示例1: random_sample_seq

# 需要导入模块: import dimod [as 别名]
# 或者: from dimod import Vartype [as 别名]
def random_sample_seq(size, vartype):
    """Return a random sample.

    Args:
        size (int):
            Sample size (number of variables).

        vartype (:class:`dimod.Vartype`):
            Variable type; for example, `Vartype.SPIN`, `BINARY`, or `{-1, 1}`.

    Returns:
        dict: Random sample of `size` in length, with values from `vartype`.

    Examples:
        >>> random_sample_seq(4, dimod.BINARY)      # doctest: +SKIP
        {0: 0, 1: 1, 2: 0, 3: 0}

    """
    values = list(vartype.value)
    return {i: random.choice(values) for i in range(size)} 
开发者ID:dwavesystems,项目名称:dwave-hybrid,代码行数:22,代码来源:utils.py

示例2: generate_random_chimera_problem

# 需要导入模块: import dimod [as 别名]
# 或者: from dimod import Vartype [as 别名]
def generate_random_chimera_problem(adjacency, h_range, j_range, offset=0, vartype=dimod.BINARY):
    """Generate a random chimera problem, with
    h int chosen randomly from h_range, j int chosen randomly from j_range.

    Typically: h_range = [0, 0] and j_range = [-k, +k].

    Args:
        adjacency (dict[/{node: {neighbor_node_1, ...}}): Adjacency dictionary
        h_range (tuple/(upper,lower)): bounds for h
        j_range (tuple/(upper,lower)): bounds for j
        offset (float): energy offset
        vartype (dimod.Vartype): BQM's vartype
    
    Returns:
        dimod.BinaryQuadraticModel
    """

    h = {n: random.randint(*h_range) for n in adjacency.keys()}
    J = {(n,e): random.randint(*j_range)
            for n, edges in adjacency.items()
                for e in edges
                    if e > n}

    return dimod.BinaryQuadraticModel(h, J, offset, vartype) 
开发者ID:dwavesystems,项目名称:dwave-hybrid,代码行数:26,代码来源:generate.py

示例3: energy

# 需要导入模块: import dimod [as 别名]
# 或者: from dimod import Vartype [as 别名]
def energy(self, solution, vartype, feed_dict=None):
        """Returns energy of the solution.
        
        Args:
            solution (list[bit]/dict[label, bit]/dict[index, bit]):
                The solution returned from solvers.
            
            vartype (:class:`dimod.Vartype`/str/set, optional):
                Variable type of the solution.
                Accepted input values:
                
                * :class:`.Vartype.SPIN`, ``'SPIN'``, ``{-1, 1}``
                * :class:`.Vartype.BINARY`, ``'BINARY'``, ``{0, 1}``
            
            feed_dict (dict[str, float]):
                Specify the placeholder values.
        
        Returns:
            float: energy of the solution. 
        """
        dict_binary_solution = self._parse_solution(solution, vartype)
        bqm = self.compiled_qubo.evaluate(feed_dict)
        return bqm.energy(dict_binary_solution) 
开发者ID:recruit-communications,项目名称:pyqubo,代码行数:25,代码来源:model.py

示例4: load

# 需要导入模块: import dimod [as 别名]
# 或者: from dimod import Vartype [as 别名]
def load(fp, cls=BinaryQuadraticModel, vartype=None):
    """Load a COOrdinate formatted binary quadratic model from a file."""
    pattern = re.compile(_LINE_REGEX)
    vartype_pattern = re.compile(_VARTYPE_HEADER_REGEX)

    triplets = []
    for line in fp:
        triplets.extend(pattern.findall(line))

        vt = vartype_pattern.findall(line)
        if vt:
            if vartype is None:
                vartype = vt[0]
            else:
                if isinstance(vartype, str):
                    vartype = Vartype[vartype]
                else:
                    vartype = Vartype(vartype)
                if Vartype[vt[0]] != vartype:
                    raise ValueError("vartypes from headers and/or inputs do not match")

    if vartype is None:
        raise ValueError("vartype must be provided either as a header or as an argument")

    bqm = cls.empty(vartype)

    for u, v, bias in triplets:
        if u == v:
            bqm.add_variable(int(u), float(bias))
        else:
            bqm.add_interaction(int(u), int(v), float(bias))

    return bqm 
开发者ID:dwavesystems,项目名称:dimod,代码行数:35,代码来源:coo.py

示例5: assert_consistent_constraint

# 需要导入模块: import dimod [as 别名]
# 或者: from dimod import Vartype [as 别名]
def assert_consistent_constraint(const):
    assert isinstance(const, Constraint)

    assert hasattr(const, 'configurations')
    assert isinstance(const.configurations, frozenset)

    assert hasattr(const, 'func')
    assert callable(const.func)

    assert hasattr(const, 'variables')
    assert isinstance(const.variables, tuple)

    assert len(const) == len(const.variables)

    assert hasattr(const, 'vartype')
    assert isinstance(const.vartype, Vartype)

    for config in const.configurations:
        assert isinstance(config, tuple)
        assert len(config) == len(const.variables)

        msg = "config {} does not match constraint vartype '{}'".format(config, const.vartype)
        assert set(config).issubset(const.vartype.value), msg

        assert const.func(*config), 'Constraint.func does not evaluate True for {}'.format(config)
        assert const.check(dict(zip(const.variables, config)))

    for config in itertools.product(const.vartype.value, repeat=len(const)):
        if config in const.configurations:
            assert const.func(*config)
            assert const.check(dict(zip(const.variables, config)))
        else:
            assert not const.func(*config)
            assert not const.check(dict(zip(const.variables, config))) 
开发者ID:dwavesystems,项目名称:dwavebinarycsp,代码行数:36,代码来源:testing.py

示例6: _parse_solution

# 需要导入模块: import dimod [as 别名]
# 或者: from dimod import Vartype [as 别名]
def _parse_solution(self, solution, vartype):
        """Parse solution.
        
        Args:
            solution (list[bit]/dict[label, bit]/dict[index, bit]):
                The solution returned from solvers.
            
            vartype (:class:`dimod.Vartype`/str/set, optional):
                Variable type of the solution. Accepted input values
                    * :class:`.Vartype.SPIN`, ``'SPIN'``, ``{-1, 1}``
                    * :class:`.Vartype.BINARY`, ``'BINARY'``, ``{0, 1}``
        
        Returns:
             dict[label, bit]: dictionary of label and binary bit.
        """

        if isinstance(solution, list) or isinstance(solution, np.ndarray):
            if len(self.variable_order) != len(solution):
                raise ValueError("Illegal solution. Length of the solution is different from"
                                 "that of self.variable_order.")
            dict_binary_solution = dict(zip(self.variable_order, solution))
        elif isinstance(solution, dict):

            if set(solution.keys()) == set(self.variable_order):
                dict_binary_solution = solution

            elif set(solution.keys()) == set(range(len(self.variable_order))):
                dict_binary_solution = {self.index2label[index]: v for index, v in solution.items()}

            else:
                raise ValueError("Illegal solution. The keys of the solution"
                                 " should be same as self.variable_order")
        else:
            raise TypeError("Unexpected type of solution.")

        if vartype == dimod.SPIN:
            dict_binary_solution = {k: (v + 1) / 2 for k, v in dict_binary_solution.items()}

        return dict_binary_solution 
开发者ID:recruit-communications,项目名称:pyqubo,代码行数:41,代码来源:model.py

示例7: from_func

# 需要导入模块: import dimod [as 别名]
# 或者: from dimod import Vartype [as 别名]
def from_func(cls, func, variables, vartype, name=None):
        """Construct a constraint from a validation function.

        Args:
            func (function):
                Function that evaluates True when the variables satisfy the constraint.

            variables (iterable):
                Iterable of variable labels.

            vartype (:class:`~dimod.Vartype`/str/set):
                Variable type for the constraint. Accepted input values:

                * :attr:`~dimod.Vartype.SPIN`, ``'SPIN'``, ``{-1, 1}``
                * :attr:`~dimod.Vartype.BINARY`, ``'BINARY'``, ``{0, 1}``

            name (string, optional, default='Constraint'):
                Name for the constraint.

        Examples:
            This example creates a constraint that binary variables `a` and `b`
            are not equal.

            >>> import operator
            >>> const = dwavebinarycsp.Constraint.from_func(operator.ne, ['a', 'b'], 'BINARY')
            >>> print(const.name)
            Constraint
            >>> (0, 1) in const.configurations
            True

            This example creates a constraint that :math:`out = NOT(x)`
            for spin variables.

            >>> def not_(y, x):  # y=NOT(x) for spin variables
            ...     return (y == -x)
            ...
            >>> const = dwavebinarycsp.Constraint.from_func(
            ...               not_,
            ...               ['out', 'in'],
            ...               {1, -1},
            ...               name='not_spin')
            >>> print(const.name)
            not_spin
            >>> (1, -1) in const.configurations
            True

        """
        variables = tuple(variables)

        configurations = frozenset(config
                                   for config in itertools.product(vartype.value, repeat=len(variables))
                                   if func(*config))

        return cls(func, configurations, variables, vartype, name) 
开发者ID:dwavesystems,项目名称:dwavebinarycsp,代码行数:56,代码来源:constraint.py

示例8: from_configurations

# 需要导入模块: import dimod [as 别名]
# 或者: from dimod import Vartype [as 别名]
def from_configurations(cls, configurations, variables, vartype, name=None):
        """Construct a constraint from valid configurations.

        Args:
            configurations (iterable[tuple]):
                Valid configurations of the variables. Each configuration is a tuple of variable
                assignments ordered by :attr:`~Constraint.variables`.

            variables (iterable):
                Iterable of variable labels.

            vartype (:class:`~dimod.Vartype`/str/set):
                Variable type for the constraint. Accepted input values:

                * :attr:`~dimod.Vartype.SPIN`, ``'SPIN'``, ``{-1, 1}``
                * :attr:`~dimod.Vartype.BINARY`, ``'BINARY'``, ``{0, 1}``

            name (string, optional, default='Constraint'):
                Name for the constraint.

        Examples:

            This example creates a constraint that variables `a` and `b` are not equal.

            >>> const = dwavebinarycsp.Constraint.from_configurations([(0, 1), (1, 0)],
            ...                   ['a', 'b'], dwavebinarycsp.BINARY)
            >>> print(const.name)
            Constraint
            >>> (0, 0) in const.configurations   # Order matches variables: a,b
            False

            This example creates a constraint based on specified valid configurations
            that represents an OR gate for spin variables.

            >>> const = dwavebinarycsp.Constraint.from_configurations(
            ...           [(-1, -1, -1), (1, -1, 1), (1, 1, -1), (1, 1, 1)],
            ...           ['y', 'x1', 'x2'],
            ...           dwavebinarycsp.SPIN, name='or_spin')
            >>> print(const.name)
            or_spin
            >>> (1, 1, -1) in const.configurations   # Order matches variables: y,x1,x2
            True

        """
        def func(*args): return args in configurations

        return cls(func, configurations, variables, vartype, name)

    #
    # Special Methods
    # 
开发者ID:dwavesystems,项目名称:dwavebinarycsp,代码行数:53,代码来源:constraint.py

示例9: fix_variable

# 需要导入模块: import dimod [as 别名]
# 或者: from dimod import Vartype [as 别名]
def fix_variable(self, v, value):
        """Fix the value of a variable and remove it from the constraint.

        Args:
            v (variable):
                Variable in the constraint to be set to a constant value.

            val (int):
                Value assigned to the variable. Values must match the :class:`.Vartype` of the
                constraint.

        Examples:
            This example creates a constraint that :math:`a \\ne b` on binary variables,
            fixes variable a to 0, and tests two candidate solutions.

            >>> const = dwavebinarycsp.Constraint.from_func(operator.ne,
            ...             ['a', 'b'], dwavebinarycsp.BINARY)
            >>> const.fix_variable('a', 0)
            >>> const.check({'b': 1})
            True
            >>> const.check({'b': 0})
            False

        """
        variables = self.variables
        try:
            idx = variables.index(v)
        except ValueError:
            raise ValueError("given variable {} is not part of the constraint".format(v))

        if value not in self.vartype.value:
            raise ValueError("expected value to be in {}, received {} instead".format(self.vartype.value, value))

        configurations = frozenset(config[:idx] + config[idx + 1:]  # exclude the fixed var
                                   for config in self.configurations
                                   if config[idx] == value)

        if not configurations:
            raise UnsatError("fixing {} to {} makes this constraint unsatisfiable".format(v, value))

        variables = variables[:idx] + variables[idx + 1:]

        self.configurations = configurations
        self.variables = variables

        def func(*args): return args in configurations
        self.func = func

        self.name = '{} ({} fixed to {})'.format(self.name, v, value) 
开发者ID:dwavesystems,项目名称:dwavebinarycsp,代码行数:51,代码来源:constraint.py

示例10: create

# 需要导入模块: import dimod [as 别名]
# 或者: from dimod import Vartype [as 别名]
def create(name, shape, vartype):
        """Create a new array with Spins or Binary.

        Args:
            name (str): Name of the matrix. It is used as a part of the label of variables.
                For example, if the name is 'x',
                the label of `(i, j)` th variable will be ``x[i][j]``.
            
            shape (int/tuple[int]): Dimensions of the array.
            
            vartype (:class:`dimod.Vartype`/str/set, optional):
                Variable type of the solution.
                Accepted input values:
                
                * :class:`.Vartype.SPIN`, ``'SPIN'``, ``{-1, 1}``
                * :class:`.Vartype.BINARY`, ``'BINARY'``, ``{0, 1}``

        Example:
            >>> from pyqubo import Array
            >>> array = Array.create('x', shape=(2, 2), vartype='BINARY')
            >>> array
            Array([[Binary(x[0][0]), Binary(x[0][1])],
                   [Binary(x[1][0]), Binary(x[1][1])]])
            >>> array[0]
            Array([Binary(x[0][0]), Binary(x[0][1])])
        """

        if isinstance(shape, int):
            shape = shape,

        if vartype == dimod.BINARY:
            var_class = Binary
        else:
            var_class = Spin

        def var_name(_name, index):
            return "{name}{index_repr}".format(
                name=_name, index_repr=''.join(['[%d]' % i for i in index]))

        def create_structure(index):
            return {var_name(name, index): tuple([name] + index)}

        def generator(index):
            return var_class(var_name(name, index), create_structure(index))

        return Array._create_with_generator(shape, generator) 
开发者ID:recruit-communications,项目名称:pyqubo,代码行数:48,代码来源:array.py

示例11: decode_solution

# 需要导入模块: import dimod [as 别名]
# 或者: from dimod import Vartype [as 别名]
def decode_solution(self, solution, vartype, feed_dict=None):
        """Returns decoded solution.
        
        Args:
            solution (list[bit]/dict[label, bit]/dict[index, bit]):
                The solution returned from solvers.
            
            vartype (:class:`dimod.Vartype`/str/set, optional):
                Variable type of the solution.
                Accepted input values:
                
                * :class:`.Vartype.SPIN`, ``'SPIN'``, ``{-1, 1}``
                * :class:`.Vartype.BINARY`, ``'BINARY'``, ``{0, 1}``
            
            feed_dict (dict[str, float]):
                Specify the placeholder values.
                
        Returns:
            tuple(dict, dict, float): Tuple of the decoded solution,
            broken constraints and energy.
            Structure of decoded_solution is defined by :obj:`structure`.
        """

        def put_value_with_keys(dict_body, keys, value):
            for key in keys[:-1]:
                if key not in dict_body:
                    dict_body[key] = {}
                dict_body = dict_body[key]
            dict_body[keys[-1]] = value

        decoded_solution = {}

        dict_bin_solution = self._parse_solution(solution, vartype)

        for label, bit in dict_bin_solution.items():
            if label in self.structure:
                if vartype == dimod.SPIN:
                    out_value = 2 * bit - 1
                elif vartype == dimod.BINARY:
                    out_value = bit
                put_value_with_keys(decoded_solution, self.structure[label], out_value)

        # Check satisfaction of constraints
        broken_const = {}
        for label, const in self.constraints.items():
            energy = const.energy(dict_bin_solution, feed_dict)
            if energy > 0.0:
                result_value = {var: dict_bin_solution[var] for var in
                                reduce(or_, [k.keys for k in const.polynomial.keys()])}
                broken_const[label] = {"result": result_value, "penalty": energy}
            elif energy < 0.0:
                raise ValueError("The energy of the constraint \"{label}\" is {energy}."
                                 "But an energy of constraints should not be negative."
                                 .format(label=label, energy=energy))

        problem_energy = self.energy(dict_bin_solution, dimod.BINARY, feed_dict)

        return decoded_solution, broken_const, problem_energy 
开发者ID:recruit-communications,项目名称:pyqubo,代码行数:60,代码来源:model.py


注:本文中的dimod.Vartype方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。