コード例 #1
0
def hubo_simulated_annealing(bhom: BinaryHigherOrderModel, state: list,
                             schedule: list, var_type):

    adj_dict = bhom.adj_dict()
    state = np.array(state)

    if SPIN == as_vartype(var_type):
        for beta, mc_steps in schedule:
            for _ in range(mc_steps):
                for i in bhom.indices:
                    de = -2 * state[i] * np.sum([
                        d * np.prod(state[_inds]) for _inds, d in adj_dict[i]
                    ])
                    de += -2 * state[i] * bhom.interactions[0][i]
                    if de < 0 or np.random.uniform(0, 1) < np.exp(-beta * de):
                        state[i] *= -1
        return state
    elif BINARY == as_vartype(var_type):
        for beta, mc_steps in schedule:
            for _ in range(mc_steps):
                for i in bhom.indices:
                    de = (1 - 2 * state[i]) * np.sum([
                        d * np.prod(state[_inds]) for _inds, d in adj_dict[i]
                    ])
                    de += (1 - 2 * state[i]) * bhom.interactions[0][i]
                    if de <= 0 or np.random.uniform(0, 1) < np.exp(-beta * de):
                        state[i] = 0 if state[i] == 1 else 1
        return state
    else:
        raise ValueError("var_type should be SPIN or BINARY")
コード例 #2
0
def _to_cxxcimod(vartype):
    # convert to cxxcimod type
    if isinstance(vartype, cxxcimod.Vartype):
        return vartype

    vartype = dimod.as_vartype(vartype)
    if vartype == dimod.SPIN:
        return cxxcimod.Vartype.SPIN
    if vartype == dimod.BINARY:
        return cxxcimod.Vartype.BINARY
コード例 #3
0
ファイル: model.py プロジェクト: rej55/OpenJij
    def __init__(self,
                 linear,
                 quadratic,
                 offset=0.0,
                 var_type=openjij.SPIN,
                 **kwargs):
        super().__init__(linear, quadratic, offset, var_type, **kwargs)

        self.var_type = dimod.as_vartype(var_type)

        index_set = set(self.linear.keys())
        for v1, v2 in self.quadratic.keys():
            index_set.add(v1)
            index_set.add(v2)
        self.indices = list(index_set)
        self._interaction_matrix = None  # calculated at interactions()
        self.size = len(self.indices)

        if var_type == openjij.SPIN:
            self.energy_bias = 0.0
        else:  # BINARY
            self.energy_bias = (sum(list(self.linear.values())) * 2 +
                                sum(list(self.quadratic.values()))) / 4
コード例 #4
0
ファイル: solver.py プロジェクト: randomir/dwave-cloud-client
    def reformat_parameters(vartype: '_Vartype',
                            parameters: typing.MutableMapping[str, typing.Any],
                            properties: typing.Mapping[str, typing.Any],
                            inplace: bool = False,
                            ) -> typing.MutableMapping[str, typing.Any]:
        """Reformat some solver parameters for SAPI.

        Currently the only reformatted parameter is ``initial_state``. This
        method allows ``initial_state`` to be submitted as a dictionary
        mapping the qubits to their initial value.

        Args:
            vartype: One of ``'ising'`` or ``'qubo'``. If :mod:`dimod` is
                installed, this can also be any
                :class:`~dimod.typing.VartypeLike`.
            parameters: The parameters to submit to this solver.
            properties: The solver's properties. Either
                :attr:`StructuredSolver.properties` or
                :attr:`dwave.systems.DWaveSampler.properties` can be
                provided.
            inplace: Whether to modify the ``parameters`` in-place or return
                a copy.

        Returns:
            The reformatted solver parameters.
            If ``inplace`` is true the modified ``parameters`` is returned.
            If ``inplace`` is false then a deep copy of ``parameters``
            with the relevant fields updated is returned.

        """
        # whether to copy or not
        parameters = parameters if inplace else copy.deepcopy(parameters)

        # handle the vartype
        if vartype not in ('ising', 'qubo'):
            try:
                vartype = 'ising' if dimod.as_vartype(vartype) is dimod.SPIN else 'qubo'
            except (TypeError, AttributeError):
                msg = "expected vartype to be one of: 'ising', 'qubo'"
                if dimod:
                    msg += ", 'BINARY', 'SPIN', dimod.BINARY, dimod.SPIN"
                msg += f"; {vartype!r} provided"
                raise ValueError(msg) from None

        # update the parameters
        if 'initial_state' in parameters:
            initial_state = parameters['initial_state']
            if isinstance(initial_state, typing.Mapping):

                initial_state_list = [3]*properties['num_qubits']

                low = -1 if vartype == 'ising' else 0

                for v, val in initial_state.items():
                    if val == 3:
                        continue
                    if val <= 0:
                        initial_state_list[v] = low
                    else:
                        initial_state_list[v] = 1

                parameters['initial_state'] = initial_state_list
            # else: support old format

        return parameters