Beispiel #1
0
def test_set_mapping():

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

    d = QUSO({('a', 'b'): 1, ('a',): 2})
    d.set_reverse_mapping({0: 'a', 2: 'b'})
    assert d.to_quso() == {(0, 2): 1, (0,): 2}
Beispiel #2
0
def test_properties():

    temp = QUSO({('0', '0'): 1, ('0', 1): 2})
    assert temp.offset == 1

    d = QUSO()
    d[(0,)] += 1
    d[(1,)] += 2
    assert d == d.to_quso() == {(0,): 1, (1,): 2}
    assert d.mapping == d.reverse_mapping == {0: 0, 1: 1}

    d.set_mapping({1: 0, 0: 1})
    assert d.to_quso() == {(1,): 1, (0,): 2}
    assert d.mapping == d.reverse_mapping == {0: 1, 1: 0}
Beispiel #3
0
def test_properties():

    temp = QUSO({('0', '0'): 1, ('0', 1): 2})
    assert temp.offset == 1

    d = QUSO()
    d[(0,)] += 1
    d[(1,)] += 2
    assert d == d.to_quso() == {(0,): 1, (1,): 2}
    assert d.mapping == d.reverse_mapping == {0: 0, 1: 1}

    d.set_mapping({1: 0, 0: 1})
    assert d.to_quso() == {(1,): 1, (0,): 2}
    assert d.mapping == d.reverse_mapping == {0: 1, 1: 0}

    # an old bug
    d = QUSO()
    d.set_mapping({0: 0})
    d[(0,)] += 1
    assert d.num_binary_variables == 1
    assert d.variables == {0}
Beispiel #4
0
def test_to_enumerated():

    d = QUSO({('a', 'b'): 1, ('a',): 2})
    dt = d.to_enumerated()
    assert type(dt) == QUSOMatrix
    assert dt == d.to_quso()
Beispiel #5
0
    def __init__(self, L, initial_state=None):
        """__init__.

        Parameters
        ----------
        L : dict, ``qubovert.utils.QUSOMatrix``, or ``qubovert.QUSO`` object.
            The QUSO to simulate. This should map tuples of spin variable
            labels to their respective coefficient in the Hamiltonian.
            For more information, see the docstrings for
            ``qubovert.utils.QUSOMatrix`` and ``qubovert.QUSO``.
        initial_state : dict (optional, defaults to None).
            The initial state to start the simulation in. ``initial_state``
            should map spin label names to their initial values, where each
            value is either 1 or -1. If ``initial_state`` is None, then it
            will be initialized to all 1s.

        """
        # must use type since we don't want errors from inheritance
        if type(L) == QUSOMatrix:
            N = L.max_index + 1
            model = L
            self._mapping = dict(enumerate(range(N)))
            self._reverse_mapping = self._mapping
            self._variables = set(self._mapping.keys())
        elif type(L) != QUSO:
            L = QUSO(L)

        if type(L) == QUSO:
            N = L.num_binary_variables
            model = L.to_quso()
            self._mapping = L.mapping
            self._reverse_mapping = L.reverse_mapping
            self._variables = L.variables

        self._initial_state = (initial_state.copy()
                               if initial_state is not None else
                               {v: 1
                                for v in self._variables})
        self._state = [1] * N
        self.set_state(self._initial_state)

        # C arguments
        # create model arrays
        h, num_neighbors = [0.] * N, [0] * N
        neighbors, J = [[] for _ in range(N)], [[] for _ in range(N)]

        for k, v in model.items():
            val = float(v)
            if len(k) == 1:
                h[k[0]] = val
            elif len(k) == 2:
                i, j = k
                neighbors[i].append(j)
                neighbors[j].append(i)
                num_neighbors[i] += 1
                num_neighbors[j] += 1
                J[i].append(val)
                J[j].append(val)
            # ignore offset.
        # flatten the arrays.
        J, neighbors = list(chain(*J)), list(chain(*neighbors))

        self._c_args = h, num_neighbors, neighbors, J
Beispiel #6
0
def anneal_quso(L, num_anneals=1, anneal_duration=1000, initial_state=None,
                temperature_range=None, schedule='geometric',
                in_order=True, seed=None):
    """anneal_quso.

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

    Parameters
    ----------
    L : dict, ``qubovert.utils.QUSOMatrix`` or ``qubovert.QUSO``.
        Maps spin labels to their values in the objective function.
        Please see the docstring of ``qubovert.QUSO`` for more info on how to
        format ``L``.
    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(L, spin=True)``.
    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.
    ValueError
        If ``L`` is not degree 2 or less.

    Warns
    -----
    qubovert.utils.QUBOVertWarning
        If both the ``temperature_range`` and explicit ``schedule`` arguments
        are provided.

    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_quso(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(
        L, anneal_duration, temperature_range, schedule
    )

    # must use type since we don't want errors from inheritance
    if type(L) == QUSOMatrix:
        N = L.max_index + 1
        model = L
        reverse_mapping = dict(enumerate(range(N)))
        # mapping = reverse_mapping
    elif type(L) != QUSO:
        L = QUSO(L)

    if type(L) == QUSO:
        N = L.num_binary_variables
        model = L.to_quso()
        # mapping = L.mapping
        reverse_mapping = L.reverse_mapping

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

    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
    h, num_neighbors = [0.] * N, [0] * N
    neighbors, J = [[] for _ in range(N)], [[] for _ in range(N)]

    for k, v in model.items():
        val = float(v)
        if len(k) == 1:
            h[k[0]] = val
        elif len(k) == 2:
            i, j = k
            neighbors[i].append(j)
            neighbors[j].append(i)
            num_neighbors[i] += 1
            num_neighbors[j] += 1
            J[i].append(val)
            J[j].append(val)

    # flatten the arrays.
    J, neighbors = list(chain(*J)), list(chain(*neighbors))

    states, values = c_anneal_quso(
        h, num_neighbors, neighbors, J,  # 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
    )