コード例 #1
0
def test_set_mapping():

    d = PUSO({('a', 'b'): 1, ('a', ): 2})
    d.set_mapping({'a': 0, 'b': 2})
    assert d.to_puso() == {(0, 2): 1, (0, ): 2}

    d = PUSO({('a', 'b'): 1, ('a', ): 2})
    d.set_reverse_mapping({0: 'a', 2: 'b'})
    assert d.to_puso() == {(0, 2): 1, (0, ): 2}
コード例 #2
0
def test_to_enumerated():

    d = PUSO({('a', 'b'): 1, ('a', ): 2})
    dt = d.to_enumerated()
    assert type(dt) == PUSOMatrix
    assert dt == d.to_puso()
コード例 #3
0
ファイル: _anneal.py プロジェクト: jtiosue/qubovert
def anneal_puso(H, num_anneals=1, anneal_duration=1000, initial_state=None,
                temperature_range=None, schedule='geometric',
                in_order=True, seed=None):
    """anneal_puso.

    Run a simulated annealing algorithm to try to find the minimum of the PUSO
    given by ``H``. Please see all of the parameters for details.

    **Please note** that the ``qv.sim.anneal_quso`` function performs
    faster than the ``qv.sim.anneal_puso`` function. If your system has
    degree 2 or less, then you should use the ``qv.sim.anneal_quso``
    function.

    Parameters
    ----------
    H : dict, or any type in ``qubovert.SPIN_MODELS``.
        Maps spin labels to their values in the Hamiltonian.
        Please see the docstrings of any of the objects in
        ``qubovert.SPIN_MODELS`` to see how ``H`` should be formatted.
    num_anneals : int >= 1 (optional, defaults to 1).
        The number of times to run the simulated annealing algorithm.
    anneal_duration : int >= 1 (optional, defaults to 1000).
        The total number of updates to the simulation during the anneal.
        This is related to the amount of time we spend in the cooling schedule.
        If an explicit schedule is provided, then ``anneal_duration`` will be
        ignored.
    initial_state : dict (optional, defaults to None).
        The initial state to start the anneal in. ``initial_state`` must map
        the spin label names to their values in {1, -1}. If ``initial_state``
        is None, then a random state will be chosen to start each anneal.
        Otherwise, ``initial_state`` will be the starting state for all of the
        anneals.
    temperature_range : tuple (optional, defaults to None).
        The temperature to start and end the anneal at.
        ``temperature = (T0, Tf)``. ``T0`` must be >= ``Tf``. To see more
        details on picking a temperature range, please see the function
        ``qubovert.sim.anneal_temperature_range``. If ``temperature_range`` is
        None, then it will by default be set to
        ``T0, Tf = qubovert.sim.anneal_temperature_range(H, spin=True)``.
        Note that a temperature can only be zero if ``schedule`` is explicitly
        given or if ``schedule`` is linear.
    schedule : str, or list of floats (optional, defaults to ``'geometric'``).
        What type of cooling schedule to use. If ``schedule == 'linear'``,
        then the cooling schedule will be a linear interpolation between the
        values in ``temperature_range``. If ``schedule == 'geometric'``, then
        the cooling schedule will be a geometric interpolation between the
        values in ``temperature_range``. Otherwise, ``schedule`` must be an
        iterable of floats being the explicit temperature schedule for the
        anneal to follow.
    in_order : bool (optional, defaults to True).
        Whether to iterate through the variables in order or randomly
        during an update step. When ``in_order`` is False, the simulation
        is more physically realistic, but when using the simulation for
        annealing, often it is better to have ``in_order = True``.
    seed : number (optional, defaults to None).
        The number to seed Python's builtin ``random`` module with. If
        ``seed is None``, then ``random.seed`` will not be called.

    Returns
    -------
    res : qubovert.sim.AnnealResults object.
        ``res`` contains information on the final states of the simulations.
        See Examples below for an example of how to read from ``res``.
        See ``help(qubovert.sim.AnnealResults)`` for more info.

    Raises
    ------
    ValueError
        If the ``schedule`` argument provided is formatted incorrectly. See the
        Parameters section.
    ValueError
        If the initial temperature is less than the final temperature.

    Warns
    -----
    qubovert.utils.QUBOVertWarning
        If both the ``temperature_range`` and explicit ``schedule`` arguments
        are provided.
    qubovert.utils.QUBOVertWarning
        If the degree of the model is 2 or less then a warning is issued that
        says you should use the ``anneal_qubo`` or ``anneal_quso`` functions.

    Example
    -------
    Consider the example of finding the ground state of the 1D
    antiferromagnetic Ising chain of length 5.

    >>> import qubovert as qv
    >>>
    >>> H = sum(qv.spin_var(i) * qv.spin_var(i+1) for i in range(4))
    >>> anneal_res = qv.sim.anneal_puso(H, num_anneals=3)
    >>>
    >>> print(anneal_res.best.value)
    -4
    >>> print(anneal_res.best.state)
    {0: 1, 1: -1, 2: 1, 3: -1, 4: 1}
    >>> # now sort the results
    >>> anneal_res.sort()
    >>>
    >>> # now iterate through all of the results in the sorted order
    >>> for res in anneal_res:
    >>>     print(res.value, res.state)
    -4, {0: 1, 1: -1, 2: 1, 3: -1, 4: 1}
    -4, {0: -1, 1: 1, 2: -1, 3: 1, 4: -1}
    -4, {0: 1, 1: -1, 2: 1, 3: -1, 4: 1}

    """
    if num_anneals <= 0:
        return AnnealResults()

    Ts = _create_spin_schedule(
        H, anneal_duration, temperature_range, schedule
    )

    # must use type since we don't want errors from inheritance
    if type(H) in (QUSOMatrix, PUSOMatrix):
        N = H.max_index + 1
        model = H
        reverse_mapping = dict(enumerate(range(N)))
    elif type(H) not in (QUSO, PUSO, PCSO):
        H = PUSO(H)

    if type(H) in (QUSO, PUSO, PCSO):
        N = H.num_binary_variables
        model = H.to_puso()
        reverse_mapping = H.reverse_mapping

    if model.degree <= 2:
        QUBOVertWarning.warn(
            "The input problem has degree <= 2; consider using the "
            "``qubovert.sim.anneal_qubo`` or ``qubovert.sim.anneal_quso`` "
            "functions, which are significantly faster than this function "
            "because they take advantage of the low degree."
        )

    # solve `model`, convert solutions back to `H`

    if not N:
        return AnnealResults(
            AnnealResult({}, model.offset, True) for _ in range(num_anneals)
        )

    if initial_state is not None:
        init_state = [1] * N
        for k, v in reverse_mapping.items():
            init_state[k] = initial_state[v]
    else:
        init_state = []

    # create arguments for the C function
    # create terms and couplings
    terms, couplings, num_couplings = [], [], []
    for term, coupling in model.items():
        if term:
            couplings.append(float(coupling))
            terms.extend(term)
            num_couplings.append(len(term))

    states, values = c_anneal_puso(
        N, num_couplings, terms, couplings,  # describe the problem
        Ts, num_anneals, int(in_order), init_state,  # describe the algorithm
        seed if seed is not None else -1
    )
    return _package_spin_results(
        states, values, model.offset, reverse_mapping
    )